在mongoose/mongodb/node中使用异步回调循环 [英] Loop with asynchronous callbacks in mongoose/mongodb/node

查看:61
本文介绍了在mongoose/mongodb/node中使用异步回调循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是nodejs/mongo/mongoose的新手,我正在尝试做一件非常简单的事情.我有以下架构:

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: 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,名称和书数的作者列表.我有这样的东西:

I want to create a list of authors with id, name and book count for each author. I have something like this:

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方式实现此功能的正确方法是什么?

I know how to do a query for the count. My problem is how to do a loop of the authors and populate the output with asynchronous callbacks. What is the proper way to implement this in nodejs fashion?

谢谢

推荐答案

我认为您想使用类似异步以协调这些请求; map()似乎是一个不错的选择:

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);
    }
  });
});

这篇关于在mongoose/mongodb/node中使用异步回调循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆