0.1.2 • Published 10 years ago

mongoose-l2r v0.1.2

Weekly downloads
1
License
MIT
Repository
github
Last release
10 years ago

mongoose-l2r

build status Dependencies NPM version

NPM

A REST-style link builder for mongoose. Useful if you are rolling your own REST like app.

  • Supports nested resources
  • Support alternate ids, instead of default id and _id
  • Creates link map for all relations

Install

npm install --save mongoose-l2r

Usage

modelInstance.toLink([array of parents], { options object });

Simple case

var l2r = require('mongoose-l2r');

var PostSchema = new Schema({
    ....
});

PostSchema.plugin(l2r);

var Post = mongoose.model('Post', PostSchema);
var post = new Post;

... save your post ...

post.toLink(); // returns: /posts/:post_id

Nested resources

Assume you have a Comment model that are comments to Posts. You can build URLs like this:

/posts/:post_id/comments/:comment_id

.. by doing like this:

comment.toLink();
// returns: /comment/:comment_id

comment.toLink([post]);
// returns: /posts/:post_id/comments/:comment_id

Note: Only the model on which the method is invoked on needs to have the plugin installed.

Alternate names option

You can use different paths than those based on model names like so:

comment.toLink([post], { posts_path: 'entries' });
// returns: /entries/:post_id/comments/:comment_id

Alternate id option

By default the plugin will look for _id and id. If you want to use another property for id, specify it like this:

post.toLink({ id: 'uid' });

Note: You cannot specify a different id property for each model in the path.

ObjectId to link

Can also be used on ObjectIds. Suppose our Post instance had a comments relation and instead of resturning popluated comments you would return URLs to them:

var PostSchema = new Schema({
    comments: [Schema.Types.ObjectId]
});
post.idToLink(post.comments, 'Comment', [post]);
// returns: [ '/posts/:post_id/comments/:comment_id1', '/posts/:post_id/comments/:comment_id2', ... ]

Relations to link

You can also turn all relations on an object into links using:

post.relationsToLink();

In our example this would return an object map to each relation:

{
    comments: [
        /posts/:post_id/comments/:comment_id1,
        /posts/:post_id/comments/:comment_id2
    ]
}

In the reverse you have to pass in which paths are the owner of the object (which the current object belongs to):

comment1.relationsToLink(['post']);

Resulting in:

{
    post: /posts/:post_id/
}

Common Pitfalls

This plugin attaches itself ot schema.methods, so if you set the methods on a scehma like the following, be sure to add the plugin after setting the methods:

PostSchema.methods = {
    ...
};

PostSchema.plugin(l2r);

TODO

  • Add more tests.
  • Make convenience methods for a models relations.
  • Handle case where a schema contains custome Schemas and no ref option.