I’m serving a JSON API for posts, where I want to deliver the post object after linking it to the appropriate user model.
I’m having a MongoDB schema like this:
User = {
email: String,
password: String
};
Post = {
user: ObjectId,
text: String
};
I don’t find a problem linking a single post, which I’ve done using the following code (I’m using Mongoose and Express):
app.get('/api/posts/:id', function(req, res){
return Post.findById(req.params.id, function(err, post) {
if (!err) {
User.findById(post.user, function(err, user){
var joinedpost = {
text : post.text,
user : user
};
return res.send(joinedpost);
});
}
});
});
However, when I want to server multiple posts I face the following problem: Since I’m working in an asynchronous environment I can’t simply fetch all posts and iterate over them to link each post to its user.
So I think I should write two queries, one that fetches the posts, and the other links them all at once, so that I can serve them immediately. Am I correct? And if so, how can I achieve that?
The
$inoperator will let you do this in one query. Here’s how I’d do it (assuming you use underscore):This isn’t well tested, and you’d need to handle the error condition on the
User.findcall, but it should be a good starting point.Also, the
asynclibrary helps a lot with stuff like this. You might look into that and something like thewaterfallmethod to get around the crazy nested callback problem.