Mongoose Populate Child ref返回null数组

正在检查Mongoose和相对较新的填充方法。 从孩子向父母填充时似乎工作完美,如下所示:

var Comment = new Schema({ Message: { type: String } User: { type: ObjectId, ref: 'User' } }); var User = new Schema({ Username: { type: String } Comments: [{ type: ObjectId, ref: 'Comment' }] }); 

以下按预期工作。

 Comment.find({}).populate({ path: 'User' }).exec(function (err, comments) { if(err) handle(callback); // no error do something with comments/user. // this works fine and populates the user perfectly for each comment. }); User.findOne({ Username: "some username"}).populate('Comments').exec(function (err, user) { if(err) handle(callback); // this throws no errors however the Comments array is null. // if I call this without populate I can see the ref ObjectIds in the array. }); 

事实上,ObjectIds是可见的,没有调用在用户模型/模式上填充,事实上,我可以填充从儿童边ref正好使得它似乎configuration是正确的,但没有喜悦。

上面的模式被缩短了,所以不要发布一长长的代码列表(我讨厌!!!)。 希望我错过了简单的事情。

确定整理了这一点。 不幸的是,像许多文件一样,文件并不总是很清楚。 为了在两个方向使用“填充”。 这是孩子到父母,相反,父母到孩子,你必须仍然推你的孩子项目到父母的数组。 这些当然是文档,而不是关系数据库,所以基本上填充是一个伪关系关系,或者至less这是我如何看待它,虽然我有组件正确configuration我的序列本来是不正确的。 底线不是太复杂,我不得不从逻辑上思考这个问题。 所以在这里,你去下一个乔…

注:我原来的问题的查找方法是正确的,这是最初保存到数据库是不准确的,并导致父到孩子人口。

  user.save(function (err) { comment.User = user._id; comment.save(function (err) { user.Comments.push(comment); user.save(function (err) { if (err) { res.json(400, { message: err + '' }); } else { res.json(200, { message: 'success' }); } }); }); });