为了填充引用的子文档,您需要显式定义ID所引用的文档集合(如
created_by: { type: Schema.Types.ObjectId, ref:'User' })。假设已定义了此引用,并且在其他方面也对您的架构进行了很好的定义,那么您现在可以
populate照常调用(例如
populate('comments.created_by'))概念证明代码:
// Schemavar mongoose = require('mongoose');var Schema = mongoose.Schema;var UserSchema = new Schema({ name: String});var CommentSchema = new Schema({ text: String, created_by: { type: Schema.Types.ObjectId, ref: 'User' }});var ItemSchema = new Schema({ comments: [CommentSchema]});// Connect to DB and instantiate models var db = mongoose.connect('enter your database here');var User = db.model('User', UserSchema);var Comment = db.model('Comment', CommentSchema);var Item = db.model('Item', ItemSchema);// Find and populateItem.find({}).populate('comments.created_by').exec(function(err, items) { console.log(items[0].comments[0].created_by.name);});最后请注意,该方法
populate仅适用于查询,因此您需要先将项目传递到查询中,然后再调用它:
item.save(function(err, item) { Item.findOne(item).populate('comments.created_by').exec(function (err, item) { res.json({ status: 'success', message: "You have commented on this item", comment: item.comments.id(comment._id) }); });});


