我是 nodejs/mongo/mongoose 的新手,我正在尝试做一件非常简单的事情。我有以下架构:
var authorSchema = mongoose.Schema({
name: String,
});
Author = mongoose.model('Author', authorSchema);
var bookSchema = mongoose.Schema({
title: String,
isbn: String,
pages: Number,
author: { type : mongoose.Schema.ObjectId, ref : 'Author', index: true }
});
Book = mongoose.model('Book', bookSchema);
我想创建一个作者列表,其中包含每位作者的 ID、姓名和图书数量。我有这样的东西:
exports.author_list = function(req, res){
Author.find({}, function (err, authors){
var author_array = Array();
for (var i=0;i<authors.length;i++){
var author_obj = new Object();
author_obj.id = authors[i]._id;
author_obj.name = authors[i].name;
author_obj.count = 0; //here is the problem
author_array[i] = author_obj;
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify({ authors: author_array }));
res.end();
});
}
我知道如何查询计数。我的问题是如何执行作者循环并使用异步回调填充输出。以 nodejs 方式实现它的正确方法是什么?
谢谢
最佳答案
我想你会想使用像 async 这样的东西协调这些请求; map()似乎是一个不错的选择:
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);
}
});
});
关于node.js - 在 mongoose/mongodb/node 中使用异步回调循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16119855/