I am new to nodejs/mongo/mongoose and i am trying to do a very simple thing. I have the following schemas:
var authorSchema = mongoose.Schema({
name: Str
I think you'd want to use something like async to coordinate those requests; map() seems to be a good choice:
Author.find({}, function (err, authors) {
async.map(authors, function(author, done) {
Book.count({author: author._id}, function(err, count) {
if (err)
done(err);
else
{
done(null, {
id : author._id,
name : author.name,
count : count
});
}
});
}, function(err, author_array) {
if (err)
{
// handle error
}
else
{
/*
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify({ authors: author_array }));
res.end();
*/
// Shorter:
res.json(author_array);
}
});
});