Mongo子文档人口

你好,我有三个模型

post:

var PostSchema = new Schema({ title: { type: String, required: true, default: '', }, content: { type: String, required: true, default: '', }, community: { type: String, default: '', }, price: { type: String, required: true, default: '', }, location: { type: String, required: true, default: '', }, images: { type:[], required: true, }, user: { type: Schema.ObjectId, required: true, ref: 'User', }, accepted : { type: [], }, comments: { type: [Schema.Types.ObjectId], ref:"Comment" } }); 

用户:

 var userSchema = mongoose.Schema({ local : { email : String, password : String, }, firstName: { type: String, required: true }, lastName: { type: String, required: true }, location: { type: String, required: true }, profilepicture: { type: String }, }); 

注释

 var CommentSchema = new Schema({ title: { type: String, default: '', }, content: { type: String, default: '', }, user: { type: Schema.ObjectId, ref: 'User' }, post: { type: Schema.ObjectId, ref: 'Post' }, offer: { type: String, default: '', } }); 

我试图让post模型有一个对象id数组的评论和评论有用户objectid填充。 我使用下面的代码为我的post路线,我可以得到所有的意见填充,但我不能让用户的评论填充。理论上这应该根据mongo文档工作,但它不是。 有任何想法吗?

 app.get('/api/posts', function(req, res) { Post.find().populate('user comments comments.user').exec(function(err, posts) { if (err) { res.render('error', { status: 500 }); } else { res.jsonp(posts); } }); }); 

要做你想做的事情,在初始填充调用完成之后,你需要调用内部的“comments”对象。 在您的列表的简化版本中:

 var async = require("async"), mongoose = require("mongoose"), Schema = mongoose.Schema; mongoose.connect("mongodb://localhost/user"); var postSchema = new Schema({ title: { type: String, required: true, default: '' }, user: { type: Schema.Types.ObjectId, required: true, ref: 'User' }, comments: [{ type: Schema.Types.ObjectId, ref: "Comment" }] }); var userSchema = new Schema({ name: String }); var commentSchema = new Schema({ content: String, user: { type: Schema.Types.ObjectId, ref: "User" }, post: { type: Schema.Types.ObjectId, ref: "Post" } }); var Post = mongoose.model( "Post", postSchema ); var User = mongoose.model( "User", userSchema ); var Comment = mongoose.model( "Comment", commentSchema ); 

在注释中填充“用户”将如下所示:

 Post.find().populate("user comments").exec(function(err,docs) { async.forEach(docs,function(doc,callback) { Comment.populate( doc.comments,{ "path": "user" },function(err,output) { //console.log( "doc: " + doc ); //console.log( "proc: " + output ); callback(); }); },function(err) { console.log( "all: " + JSON.stringify(docs,undefined,4 )); }); }); 

或者,您实际上正在处理您在post中find的结果。 重点是你的“注释”需要先填充,然后你可以调用.populate() ,使用模型的forms,在结果每个文件的整个“评论”数组。