Looking for a more efficient way of doing many queries in mongoose-q Looking for a more efficient way of doing many queries in mongoose-q mongoose mongoose

Looking for a more efficient way of doing many queries in mongoose-q


Why do you reproduce the pyramid which is typical of callbacks?

I would suggest rewriting the code as follows. There is only one error handler (fail fn), check if it could fit your needs. Note you have to include the q library.

q = require('q');User.findById(toFollowId)    .execQ()    .then(function(user){        if (!user) return res.send(404);        user.followers.addToSet(me);        me.following.addToSet(user);        return q.all([me.saveQ(), user.saveQ()]);    })    .spread(function(me, user){        getFollowerStats([me, user], function(err, data){            if ( err ) return res.json(400, err);            res.json(data);        });    })    .fail(function(err){        next(err);    });

A note regarding spread:

If you have a promise for an array, you can use spread as a replacement for then. The spread function “spreads” the values over the arguments of the fulfillment handler. The rejection handler will get called at the first sign of failure. That is, whichever of the received promises fails first gets handled by the rejection handler.

See the doc (http://documentup.com/kriskowal/q/) for a complete description.

Here is an alternative using "then":

User.findById(toFollowId)    .execQ()    .then(function(user){        if (!user) return res.send(404);        user.followers.addToSet(me);        me.following.addToSet(user);        return q.all([me.saveQ(), user.saveQ()]);    })    .then(function(resolvedArray){        var me = resolvedArray[0],            user = resolvedArray[1];        getFollowerStats([me, user], function(err, data){            if ( err ) return res.json(400, err);            res.json(data);        });    })    .fail(function(err){        next(err);    });