我有两个模型;一个用于用户,另一个用于StudyGroup。每个StudyGroup都有一个唯一的guid
字段。用户模型有一个studyGroups字段,它是字符串guid
的数组。一个用户可以加入多个学习组。
用户模型
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模型
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' }],
});
我想使用存储在数组中的字符串
studyGroup
在用户模型的guid
数组中找到所有studyGroups。然后将相应的studyGroup对象发送到前端。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": "$resultingStudyGroupsArray" },
"count": { "$sum": 1 }
}
}
]).exec(function(err, results){
console.log(results);
return res.json({ studyGroups: results });
});
}
但是,上面的代码只是返回一个空数组。但是我想返回一个studyGroup对象数组。
最佳答案
foreignField
应该是guid
。
export function getUserStudyGroups(req, res) { User.aggregate([
{ "$unwind": "$studyGroups" },
{
"$lookup": {
"from": "studyGroups",
"localField": "studyGroups",
"foreignField": "guid",
"as": "resultingStudyGroupsArray"
}
},
{ "$unwind": "$resultingStudyGroupsArray" },
{
"$group": {
"_id": null,
"myStudyGroups": { "$addToSet": "$resultingStudyGroupsArray" },
"count": { "$sum": 1 }
}
} ]).exec(function(err, results){
console.log(results);
return res.json({ studyGroups: results }); }); }