Return certain fields with .populate() from Mongoose

前端 未结 10 1825
栀梦
栀梦 2021-01-30 10:11

I\'m getting returned a JSON value from MongoDB after I run my query. The problem is I do not want to return all the JSON associated with my return, I tried searching the docs a

10条回答
  •  臣服心动
    2021-01-30 10:45

    Hi for me it worked for me i populated user field using the populate code : --->

    async function displayMessage(req,res,next){
        try{
            let data= await Msg.find().populate("user","userName userProfileImg","User")
                   if(data===null) throw "Data couldn ot be loaded server error"
            else {
                res.status(200).json(data)
            }
        }   catch(err){
                next(err)
        }
    }
    

    i am directly getting the result . Here the fields userName , userProfile image are the ones that ive required selectively and the syntax for populate is :-->

     .populate("user field to populate","fields to display with spaces between each of them " , "modelName ")
    

    every parameter should be in inverted comma's.

    Below is the output i recieve.One more thing you don't have to worry about the populating sub-document id you will automatically get them.

    [
        {
            "_id": "5e8bff324beaaa04701f3bb9",
            "text": "testing message route",
            "user": {
                "_id": "5e8bf062d3c310054cf9f293",
                "userName": "boss",
                "userProfileImg": "img"
            },
            "__v": 0
        },
        {
            "_id": "5e8bff8dd4368a2858e8f771",
            "text": "testing message route second",
            "user": {
                "_id": "5e8bf062d3c310054cf9f293",
                "userName": "boss",
                "userProfileImg": "img"
            },
            "__v": 0
        },
        {
            "_id": "5e8c0c08e9bdb8209829176a",
            "text": "testing message route second",
            "user": {
                "_id": "5e8bf062d3c310054cf9f293",
                "userName": "boss",
                "userProfileImg": "img"
            },
            "__v": 0
        },
        {
            "_id": "5e8c0e0bcb63b12ec875962a",
            "text": "testing message route fourth time",
            "user": {
                "_id": "5e8bf062d3c310054cf9f293",
                "userName": "boss",
                "userProfileImg": "img"
            },
            "__v": 0
        }
    ]
    

提交回复
热议问题