填充嵌套引用mongoosejs的更好方法

时间:2015-07-31 13:23:33

标签: javascript node.js mongodb mongoose mongoose-populate

我正在尝试填充嵌套在其他引用中的引用。我有它的工作,但它似乎有点hacky,并想知道是否有任何其他方法来实现这一目标:

return Q.ninvoke(BoardSchema, 'find', {'_id': id}).then(function(board) {
    return Q.ninvoke(BoardSchema, 'populate', board, {path: 'lanes'}).then(function(board){
        return Q.ninvoke(LaneSchema, 'populate', board[0].lanes, {path: 'cards'}).then(function(lanes){
            board.lanes = lanes;
            return board;
        });
    });
});

是否有一些方法可以填充所有引用,或者将第二个填充作为电路板调用的一部分返回,而不像我现在那样手动设置它?

2 个答案:

答案 0 :(得分:1)

你应该可以填充多个来填充嵌套文档,如下所示:

Array
( 
    [user1] => Array
    (
        [total1] => 'totalWeek1', 'totalWeek2', 'totalWeek3'...
        [total2] => 'totalWeek1', 'totalWeek2', 'totalWeek3'...
        [total3] => 'totalWeek1', 'totalWeek2', 'totalWeek3'...
    )
    [user2] => Array
    (
        [total1] => 'totalWeek1', 'totalWeek2', 'totalWeek3'...
        [total2] => 'totalWeek1', 'totalWeek2', 'totalWeek3'...
        [total3] => 'totalWeek1', 'totalWeek2', 'totalWeek3'...
    )
    ...
) AFTER SUM THIS VALUES AND PUT IN VARIABLES $total1, $total2, $total3

这要求在模式定义中设置ref。

如果这不起作用,说实话大多数时候都是出于某种原因,你可以链接你的发现。但这与您的代码没什么不同。

Item.find({}).populate('foo foo.child').exec(function(err, items) {
    // Do something here
});

答案 1 :(得分:0)

基于Gideon的回应

Item.find({ _id: id})
  .populate({
    path: 'foo',
    model: 'FooModel',
    populate: {
      path: 'child',
      model: 'ChildModel'
    }
  })
  .exec(function(err, items) {
  // ...
});