具有多个子路径的猫鼬填充路径

时间:2016-03-12 13:31:18

标签: mongoose mongoose-populate mongoose-schema

想象一下,我有以下型号:

# MODEL A
schemaA = mongoose.Schema
    _bId:
        type: mongoose.Schema.Types.ObjectId
        ref: "B"

# MODEL B
schemaB = mongoose.Schema
    _cId:
        type: mongoose.Schema.Types.ObjectId
        ref: "C"
    _dId:
        type: mongoose.Schema.Types.ObjectId
        ref: "D"

# MODEL C
schemaC = mongoose.Schema
    _eId:
        type: mongoose.Schema.Types.ObjectId
        ref: "E"

模型D和E没有任何其他对象引用,因此不再列出为方便起见。

填充模型的最佳做法是什么?#34; A"所有参考? 目前我按如下方式解决此任务(这是一个实例方法,因为我经常需要它):

schemaA.methods =
    populateAll: (cb) ->
       @
        .populate
            path:  "_bId"
            model: "B"
            populate:
                path: "_cId"
                model: "C"
                populate:
                    path: "_eId"
                    model: "E"
        , (error) =>
            return cb error, @ if error?
            D.findById @._bId._dId
            .exec (error, d) =>
                return cb error, @ if error?

                @._bId._dId = d
                return cb error, @

这是我发现填充所有引用的唯一方法,因为填充多个路径然后再次在不同模型中的多个路径是非常困难的。我已经尝试过类似下面的解决方案,但可以想象,它只会覆盖以前的人群:

 @
 .populate
     path:  "_bId"
     model: "B"
     populate:
         path: "_cId"
         model: "C"
         populate:
             path: "_eId"
             model: "E"
 .populate
     path:  "_bId"
     model: "B"
     populate:
         path: "_dId"
         model: "D"

1 个答案:

答案 0 :(得分:2)

   @
    .populate
        path:  "_bId"
        model: "B"
        populate: [
            {
                path: "_cId"
                model: "C"
                populate:
                    path: "_eId"
                    model: "E"
            }
            {
                path: "_dId"
            }
        ]
    , (error) =>

此解决方案完全正常,我刚刚发现了这一点。