How to write multiple queries in a row?
Like a
Space.findOne({ _id: id }, function(err, space) {
User.findOne({ user_id: userid }, function(err, user) {
res.json({ space: space, user: user});
});
});
does not look good with more requests and logic
How is it done correctly?
I heard something about the promise, but I do not know.
Thanks
When I've had a similar issue, I've used the async library.
async.parallel([
function(callback){
Space.findOne({ _id: id }, callback);
},
function(callback){
User.findOne({ user_id: userid },callback);
}
],
function(err, results){
res.json({space:results[0],user:results[1]});
});
You can also use async.series if you want sequential execution.
@Benjamin's approach is correct. Mongoose also provides the populate method, which fetches multiple objects that are related to each other by their id. This also happens in parallel and is a special case of multiple queries. See http://mongoosejs.com/docs/populate.html for more examples.