Mongoose populating path with multiple subpaths
Asked Answered
C

1

6

Imagine i have the following models:

# 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"

Model D and E do not have any other object references and for the sake of convenience are therefore not listed anymore.

What is the best practice to populate model "A" with all references? Currently i resolve this task as follows (it is an instance-method because i need it quite often):

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, @

This is the only way i found to populate all references because populating multiple paths with then again multiple paths in different models is quite difficult. I already tried a solution like the one below but as one can imagine, it would only overwrite previous populations:

 @
 .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"
Chihli answered 12/3, 2016 at 13:31 Comment(0)
C
4
   @
    .populate
        path:  "_bId"
        model: "B"
        populate: [
            {
                path: "_cId"
                model: "C"
                populate:
                    path: "_eId"
                    model: "E"
            }
            {
                path: "_dId"
            }
        ]
    , (error) =>

This solution works totally fine and i just found out about this.

Chihli answered 15/3, 2016 at 20:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.