【问题标题】:Mongoose populating path with multiple subpaths具有多个子路径的猫鼬填充路径
【发布时间】:2016-06-27 18:20:10
【问题描述】:

假设我有以下模型:

# 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 没有任何其他对象引用,因此为方便起见不再列出。

用所有引用填充模型“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"

【问题讨论】:

    标签: mongoose mongoose-populate mongoose-schema


    【解决方案1】:
       @
        .populate
            path:  "_bId"
            model: "B"
            populate: [
                {
                    path: "_cId"
                    model: "C"
                    populate:
                        path: "_eId"
                        model: "E"
                }
                {
                    path: "_dId"
                }
            ]
        , (error) =>
    

    这个解决方案工作得很好,我刚刚发现了这一点。

    【讨论】:

      猜你喜欢
      • 2021-04-15
      • 2019-07-06
      • 2020-12-25
      • 1970-01-01
      • 2021-05-21
      • 2020-05-31
      • 1970-01-01
      • 2014-09-20
      • 2020-11-09
      相关资源
      最近更新 更多