node.js - 在 mongoose/mongodb/node 中使用异步回调循环

标签 node.js mongodb mongoose

我是 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/

相关文章:

node.js - 使用node.js上传文件到S3

Mongodb Admin 无法在另一个数据库中运行命令(错误代码 13)

mongodb - 从 $elemMatch 查询返回数组索引

node.js - 具有 Mongoose 聚合和求和嵌套字段的 Node

javascript - Mongoose :如何更新数组中的现有元素?

node.js - 您可以更新 Node :latest吗

node.js - 我不知道为什么我的 http 请求在我的 Angular 项目中不起作用?

c# - Mongo C# Driver 2.0 聚合组异常

javascript - 在 ubuntu windows 10 中使用 NPM 和 zsh shell

python - 在 Meteor 运行时,如何从另一个客户端访问 Meteor 的 MongoDB?