Mongoose populate embedded

后端 未结 4 2126
栀梦
栀梦 2020-12-06 09:17

I use Mongoose.js and cannot solve problem with 3 level hierarchy document.

There 2 ways to do it.

First - without refs.

C =         


        
4条回答
  •  臣服心动
    2020-12-06 09:56

    As of Mongoose 3.6 the ability to recursively populate related documents in a query has been added. Here is an example of how you might do it:

     UserList.findById(listId)
             .populate('refUserListItems')
             .exec(function(err, doc){
                 UserListItem.populate(doc.refUserListItems, {path:'refSuggestion'},
                       function(err, data){
                            console.log("User List data: %j", doc);
                            cb(null, doc);
                       }
                 );     
              });           
    

    In this case, I am populating an array of id's in 'refUserListItems' with their referenced documents. The result of the query then gets passed into another populate query that references the field of the original populated document that I want to also populate - 'refSuggestion'.

    Note the second (internal) populate - this is where the magic happens. You can continue to nest these populates and tack on more and more documents until you have built your graph the way you need it.

    It takes a little time to digest how this is working, but if you work through it, it makes sense.

提交回复
热议问题