正在查看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填充得很好的事实使得看起来配置正确但没有乐趣 .
上面的模式被缩短,以便不发布一英里长的代码列表(我讨厌!!!) . 希望我遗漏一些简单的东西 .
1 回答
好 . 把它整理出来 . 不幸的是,这与许多事情一样,文档并不总是很清楚 . 为了在两个方向上使用"populate" . 那就是Child to Parent和相反的Parent to child你 MUST 仍然将你的子项目推送到父数组 . 这些文档当然不是关系数据库,所以基本上填充是一种伪关系关系,或者至少太复杂了我只需要从逻辑上思考它 . 所以在这里你去寻找下一个乔......
注意:我的原始问题的查找方法是正确的,这是对db的初始保存不准确并导致父对子的人口 .