[ad_1]
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
}
]
[ad_2]