Reputation: 874
I have a list of users, each user have a list of exercises. I want to aggregate the basic user's info and their exercises to be displayed.
I did the following:
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Invalid username'],
unique: [true, 'This user already exists'],
},
exercises: {
type: [mongoose.Schema.Types.ObjectId],
ref: 'Exercise'
}
})
User = mongoose.model('User', userSchema);
And
const exerciseSchema = new mongoose.Schema({
user: {type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true},
description: {type:String, required: true},
duration: {type:Number, required: true},
date: {type:Date, required: true},
});
Exercise = mongoose.model('Exercise', exerciseSchema);
However, the aggregation part displays only the user's info with an empty array of exercises:
User.
find().
populate({
path: 'exercises',
model: 'Exercise'
}).
exec().
then(docs => res.json(docs).status(200)).
catch(err => res.json(err).status(500))
})
Gives:
[{
"exercises":[],
"_id":"6047b61bc7a4f702f477085b",
"name":"John Smith",
"__v":0}
]
Upvotes: 1
Views: 397
Reputation: 1045
Use the following aggregate query to get users and is exercise data.
User.aggregate([{
"$lookup":{
"localField":"exercises",
"foreignField":"_id",
"from":"Exercise",
"as" :"userExercises"
}
}])
You will get each user with its exercise data.
Upvotes: 1