Loop with asynchronous callbacks in mongoose/mongodb/node

后端 未结 1 1283
眼角桃花
眼角桃花 2021-01-01 06:40

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         


        
相关标签:
1条回答
  • 2021-01-01 07:05

    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);
        }
      });
    });
    
    0 讨论(0)
提交回复
热议问题