Mongoose从另一个集合中获取文档,该集合具有当前集合的文档作为参考

时间:2015-09-14 13:27:57

标签: node.js mongodb mongoose mongoose-populate

我在MongoDB中有两个模式,一个是作者,第二个是Book。作者有很多书。

作者架构:

var authorSchema = {
    name:{
        type: String
    },
    books:[{
        type: Schema.Types.ObjectId,
        ref: 'Book'
    }]
}

图书架构:

var bookSchema = {
    title:{
        type: String
    }
}

现在我正在创建一个图书列表页面,我想在其中使用图书集来获取每本书的所有作者。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

如果你真的要求你想要"关系"要完成"其他方式"那么anwser就是"存储"首先就是这种关系。

因此:

   var bookSchema = new Schema({
       title: { type: String },
       author: { type: Schema.Types.ObjectId }
   });

所以看看"关系"作为"双向"从某种意义上说,每个对象都具有所需的信息,以便关联"到另一个。

这基本上意味着你可以这样做:

 Books.find({ "author": authorId })
    .populate("author")
    .exec(function(err,books) {
        // stuff in here
 });

没有可怕的结构:

Books.find().execute(function(err,books) {
    var results = [];

    async.each(books,function(book,callback) { 
        Author.findOne({ "books": book._id },function(err,author) {
            var obj = book.toObject();
            book.author = author;
            results.push(books);
            callback(err);
        });            
    },
    function(err) {
        if (err) throw err;
        console.dir(results);
    });
})

原来建议做得更好。

答案 1 :(得分:1)

假设您有一本书的_id值,您可以查询作者集合,而不是图书集来获取图书的作者:

Author.find({books: book._id}, function(err, authors) { ... });
相关问题