This is My schema:
var ActivityLog = new Schema({
activity_at: { type: Date, default: Date.now },
activity_by: { type: Schema.Types.ObjectId, ref:"User" },
team_id: { type: Schema.Types.ObjectId, ref:"Team" },
activity_type: String,
activity_value: String,
msg: Object,
});
Populating the activity_by field
ActivityLog.find({}).limit(200).populate('activity_by')
.then(activities => {
res.json({success:true,activities:activities})
})
RESULT
{
"_id": "616c6bace259ac5eafe333eb",
"activity_at": "2021-10-17T18:30:04.929Z",
"time": "2021-10-17T18:30:04.929Z",
"activity_by": {
"_id": "6107e5afce6a4a0b54be97b8",
"profilePicUrl": "https://secure.gravatar.com/avatar/daed28df98c99bdaa640956e643bef3e.jpg?s=512&d=http2F%2Fa.slack-edge.com%2Fdf10d%2Fimg%2Favatars%2Fava_0004-512.png",
"user_token": null,
"name": "akshavanthm",
"email": "akshavanthm@gmail.com",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFrc2hhdmFudGhtQGdtYWlsLmNvbSIsIm5hbWUiOiJha3NoYXZhbnRobSIsIl9pZCI6IjYxMDdlNWFlMDcyZDBmNDk3YmQ0MDhkZCIsImlhdCI6MTYyNzkwNzUwMn0.S7NeE-M523i2kGX7BZo-ztHvFoQ61bvvPnXZ0vbbnKM",
"user_id": "6107e5ae072d0f497bd408dd",
"team_id": "T029FKKGT55",
"user_name": "akshavanthm",
"timezone": "Asia/Kolkata",
"user_slack_id": "U029TAAREF7",
"displayName": "",
"__v": 0,
"welcomeSent": true
},
"team_id": "612ddaa24846e87e0eda9ab6",
"activity_type": "highChart_reports",
"activity_value": "successfully sent High Chart report custom_report_2",
"msg": null,
"__v": 0
}
I am Unable to find query for matching the user_id present inside the activity_by when i use:
ActivityLog.find({"activity_by.user_id":'6107e5ae072d0f497bd408dd'}).limit(200).populate('activity_by')
.then(activities => {
res.json({success:true,activities:activities})
})
it returns null.How to access the user_id inside the activity_by(which is populated). I can only access the "_id" of the "activity_by" and not the other fields
referring to this answer on github this is not possible using populate.
you can however use aggregating with $lookup like so:
ActivityLog.aggregate([
{
$lookup: {
from:"User",
localField: "activity_by",
foreignField: "_id",
as: "yourDesiredFiledName"
}
}
])