I have two models; one for the User and the other one for the StudyGroup. Each StudyGroup has a unique guid
field. The User model has a field of studyGroups that is an array of strings guid
. A user can join multiple study groups.
User model
const userSchema = new Schema({
cuid: { type: 'String', required: true },
firstName: { type: 'String', required: true },
lastName: { type: 'String', required: true },
studentId: { type: 'Number', required: true },
password: { type: 'String', required: true },
email: { type: 'String', required: true },
dateAdded: { type: 'Date', default: Date.now, required: true },
lastLogin: { type: 'Date', default: null, required: false },
studyGroups: [{ type: 'String' }],
});
StudyGroup model
const studyGroupSchema = new Schema({
guid: { type: 'String', required: true },
groupName: { type: 'String', required: true },
course: { type: 'String', required: true },
teacher: { type: 'String', required: true },
description: { type: 'String', required: true },
dateAdded: { type: 'Date', default: Date.now, required: true },
chatMessages: [{ type: 'String' }],
});
I want to find all studyGroups in the studyGroup
array of the User model using the strings guid
stored inside the array. Then send the corresponding studyGroup objects to the Front-end.
export function getUserStudyGroups(req, res) {
User.aggregate([
{ "$unwind": "$studyGroups" },
{
"$lookup": {
"from": "studyGroups",
"localField": "studyGroups",
"foreignField": "cuid",
"as": "resultingStudyGroupsArray"
}
},
{ "$unwind": "$resultingStudyGroupsArray" },
{
"$group": {
"_id": null,
"myStudyGroups": { "$addToSet": "$resultingTagsArray" },
"count": { "$sum": 1 }
}
}
]).exec(function(err, results){
console.log(results);
return res.json({ studyGroups: results });
});
}
However, the code above just returns me an empty array. But I want to return an array of studyGroup objects.
via pbgnz
No comments:
Post a Comment