Mongoose Multipath Subpath

Imagine that 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" 

Models D and E have no other object references and, for convenience, are no longer listed.

What is the best practice to populate model “A” with all the links? I currently solve this problem as follows (this 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 to find all the links, because filling multiple paths with repeated multiple paths in different models is quite difficult. I have already tried a solution similar to the one below, but as you can imagine, it will only overwrite previous groups:

  @ .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" 
+6
source share
1 answer
  @ .populate path: "_bId" model: "B" populate: [ { path: "_cId" model: "C" populate: path: "_eId" model: "E" } { path: "_dId" } ] , (error) => 

This solution works fine, and I just found out about it.

+2
source

All Articles