Mongoose Populate Child ref返回null数组

时间:2013-05-28 02:30:22

标签: node.js mongoose populate

检查了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.
});

如果没有在User模型/架构上调用populate就可以看到ObjectIds这一事实以及我可以从子端ref充分填充的事实使得看起来配置正确但没有乐趣。

上面的模式被缩短了,以免发布一英里长的代码列表(我讨厌!!!)。希望我遗漏一些简单的东西。

1 个答案:

答案 0 :(得分:1)

O.K。把它整理出来。不幸的是,这与许多事情一样,文档并不总是很清楚。为了使用"填充"在两个方向。那就是Child to Parent和相反的Parent to child,你必须仍然将你的子项推送到父数组。这些文档当然不是关系数据库,所以基本上填充是伪关系关系,或者至少我是如何看待它的,所以虽然我已经正确配置了组件,但我的序列本来是不正确的。最重要的是,它不是太复杂,我只需要从逻辑上思考它。所以在这里你要去寻找下一个乔...

注意:我原来的问题查找方法是正确的,这是对数据库的初始保存不准确并导致父母与子女的人口。

 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' });
          }
      });             
    });             
 });