Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 在mongoose/mongodb/node中使用异步回调进行循环_Node.js_Mongodb_Mongoose - Fatal编程技术网

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

Node.js 在mongoose/mongodb/node中使用异步回调进行循环,node.js,mongodb,mongoose,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,

我是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();

    });
}
exports.author\u list=函数(req,res){
Author.find({},函数(err,authors){
var author_array=array();

对于(var i=0;i我认为您应该使用类似的方法来协调这些请求;这似乎是一个不错的选择:


什么是
Request
(似乎是一个模式,但您还没有显示它)?
requests
(用于for循环)?您想用
author\u obj.count
计算什么?你说的“作者循环并用异步回调填充输出”是什么意思?抱歉,请求是我原始代码的剩余部分。为了更清晰的示例,我将代码切换为authors/books模型。
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);
    }
  });
});