Home > Software engineering >  Return certain fields with populate() from Mongoose
Return certain fields with populate() from Mongoose

Time:06-01

I'm getting returned a JSON value from MongoDB after I run this query query. The replyID is an object of another Schema User which has _id,email and user. But I dont want the email & _id of the User and just the name. What should I add to the populate function to get the name only? Query ->

.populate({
    path: 'replies',
    populate: { path: 'replyID' }
})

JSON returned

"comments": [
    {
        "_id": "6296fcda39d113539bbe023d",
        "creator": "62948aff05bcfdb5e75df7e6",
        "postId": "62964a997c183d6c09bac126",
        "comment": "Sebastian Goattel",
        "likes": [
            "62948aff05bcfdb5e75df7e6",
            "62948f76727f0c0286949c7a"
        ],
        "replies": [
            {
                "_id": "629733dcc3220cffa7cb2049",
                "replyID": {
                        "_id": "62948f76727f0c0286949c7a",
                        "name": "Lorem Ipsum",
                        "email": "[email protected]",
                }
                "commentID": "6296fcda39d113539bbe023d",
                "reply": "Lorem Ipsum 1",
            },
            {
                "_id": "629733edc3220cffa7cb204f",
                "replyID": "62948f76727f0c0286949c7a",
                "commentID": "6296fcda39d113539bbe023d",
                "reply": "Lorem Ipsum 2",
            }
        ],
    },
],

CodePudding user response:

Try this one

.populate({
    path: 'replies',
    populate: { path: 'replyID', select: 'name -_id' }
})
  • Related