Question

I am creating a REST api using Node.js, Express.js and MongoDb.

So far so good. It is fairly easy to get things going, and I have a site up and running. But as always, it is when you get to the small details it gets hard.

I am fairly new to this stack, but I find it relatively easy to work with. Just to give you an idea of my skills.

What I am asking is this:

Let's say I have a user resource accessed from this URL:

http://localhost:3000/api/users/1234 

and it returns:

{
   "_id": 1234,
   "name": "Jay Pete",
   "self": "/users/1234"
}

I would like it to return

{
   "_id": 1234,
   "name": "Jay Pete",
   "self": "http://localhost:3000/api/users/1234"
}

With a complete fully qualified url and not just a relative one.

I don't want to save the full URL in the database. I would rather just prepend the server information at runtime. Not just for a self reference, but for every reference in my API.

But my knowledge of Express and Javascript isn't good enough for me to figure out the best way to do this yet. Would I have mongoose go it, or should I write some sort of mapper, that I invoke from the routes in Express.

How do other people do this?

Thanks, Jay

Was it helpful?

Solution

You can get this done in mongoose using virtual fields:

var Schema = new mongoose.Schema(...); //schemata
Schema.virtual('self_url').get(function() {
    return 'http://localhost:3000/api' + this.self;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top