Mongoose populate sub-sub document

后端 未结 9 1948
深忆病人
深忆病人 2021-01-30 03:00

I have this setup in my MongoDB

Items:

title: String
comments: [] // of objectId\'s

Comments:

user: ObjectId()
item: Ob         


        
相关标签:
9条回答
  • 2021-01-30 03:23

    Check the screenshot below. This thing works like charm!!!

    0 讨论(0)
  • 2021-01-30 03:27

    To add one final method that people may want to use to select only particular fields from sub-documents, you can use the following 'select' syntax:

      Model.findOne({ _id: 'example' })
        .populate({ 
          path: "comments", // 1st level subdoc (get comments)
          populate: { // 2nd level subdoc (get users in comments)
            path: "user",
            select: 'avatar name _id'// space separated (selected fields only)
          }
        })
        .exec((err, res) => { 
            // etc
         });
    
    0 讨论(0)
  • 2021-01-30 03:27

    This worked for me:

    i.e. no need for model

        .populate({
          path: 'filters',
          populate: {
            path: 'tags',
            populate: {
              path: 'votes.user'
            }
          }
        })
        .populate({
          path: 'members'
        })

    0 讨论(0)
提交回复
热议问题