node.js - Expressjs rest api how to deal with chaining functionality -


i building restful api using express, mongoose , mongodb. works fine have question how deal requests contain more functionality 1 find, delete or update in database. user model looks follows:

var userschema = new schema({   emailaddress: {type: string, unique: true},   firstname: string,   lastname: string,   password: string,   friends: [{type: schema.types.objectid, unique: true}] }); 

as can see friends array array of objectids. these objectids refer specific users in database. if want retrieve array of user's friends have user makes request, find users have same id in friends array.

now looks this:

methods.get_friends = function(req, res) {   //find user.    user.findone({_id: req.params.id}, function(err, user, next) {      if(err) next(err);     if(user) {       console.log(user);        //find friends       user.find({_id: {$in: user.friends}}, {password: 0}).exec(function (err,         friends, next) {         if(err) next(err);         if(friends) {            res.send(friends);         };       });     } 

would possible seperate lookup of user in method , chain methods? saw middleware chaining i.e. app.get('/friends', getuser, getfriend)but mean have alter req object in middleware (getuser) method , pass on? how solve issue? perhaps change mongoose model , save friend data (means become outdated) or create method getuser returns promise on collect friend data?

i grateful can get!

thank in advance.

mongoose has feature called population exists in these kinds of situations. basically, mongoose perform query/queries required load friends documents database:

user.findone({_id: req.params.id})     .populate('friends')     .exec(function(err, user) {       ...     }); 

this load related friends user.friends (as array).

if want add additional constraints (in example, password : 0), can too:

user.findone({_id: req.params.id})     .populate({       path  : 'friends'       match : { password : 0 },     })     .exec(function(err, user) {       ...     }); 

see this documentation.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -