Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose populating path with multiple subpaths

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"
like image 930
Gbeschbacher Avatar asked Mar 12 '16 13:03

Gbeschbacher


1 Answers

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

like image 179
Gbeschbacher Avatar answered Oct 21 '22 10:10

Gbeschbacher