2017-01-02 32 views
3

对不起的数组,如果标题本身就是一个矛盾:) JS初学者在这里..Node.js的遍历对象异步

我得到的MongoDB文档的数组,我想对每一个与另一个对象(从另一个表),以便我可以将这个扩展对象数组传递给我的视图。我想实现这样的事情:

exports.myFunction = function(req, res) { 
    Book.find({'good': true}).exec(function(err, docs) { // find good books 
     // add authors to each book (?): 
     for (var i = 0, i < docs.length; i++) { 
      docs[i].author = Author.findOne({'_id': docs[i].author_id}); 
     } 
     // render books: 
     res.render('/books.ejs', {books: docs}); 
    }); 
} 

我认为这不是JavaScript的方式来做到这一点:)所以我怎么能做到这一点?

感谢,

回答

2

使用$lookup功能的聚合框架中。下面的例子演示了如何运用你的情况:

exports.myFunction = function(req, res) { 
    Book.aggregate([ 
     { "$match": { "good": true } }, 
     { 
      "$lookup": { 
       "from": "authors" 
       "localField": "author_id", 
       "foreignField": "_id", 
       "as": "author" 
      } 
     }, 
     { "$unwind": "author" } 
    ]).exec(function(err, docs) { 
     res.render('/books.ejs', {books: docs}); 
    }); 
} 
1

我找到了另一种解决方案,这是使用populate

对于这一点,我需要从改变我的书模型,

var mongoose = require('mongoose'); 

var bookSchema = mongoose.Schema({ 
author_id: String, 
good: Boolean 
}); 

到:

var mongoose = require('mongoose'); 
var Author = require('./author.js'); // added this 

var bookSchema = mongoose.Schema({ 
author: { type: mongoose.Schema.Types.ObjectId, ref: 'Author' }, 
good: Boolean 
}); 

我连锁populate()我的初步查询作为如下:

exports.myFunction = function(req, res) { 
    Book.find({'good': true}).populate('author').exec(function(err, docs) { // find good books 
     // render books: 
     res.render('/books.ejs', {books: docs}); 
    }); 
}