Mongoose populate sub-sub document

后端 未结 9 1939
深忆病人
深忆病人 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: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
         });
    

提交回复
热议问题