2017-02-21 181 views
0

我对如何解决这个问题感到困惑。我想用特定的StudyGroup模型来填充我的studyGroups数组中的我的用户模型。我通过路由器(用户为cuid: req.params.cuid,研究组为guid: req.params.guid)获得特定用户和studyGroup。Mongoose使用另一个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: mongoose.Schema.Types.ObjectId, 
     ref: "studyGroup" 
     } 
    ] 
}); 

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 }, 
}); 

路线

router.route('/:cuid/studyGroups/:guid').post(UserController.addUserStudyGroups);

这里是所有动作发生的地方。首先我找到了用户,现在我想将整个studyGroup模型对象添加到数组中。所以我的想法是使用guid: req.params.guid查询studyGroup,但不知道这是否是正确的方法。

控制器

export function addUserStudyGroups(req, res) { 
    User.findOne({ cuid: req.params.cuid }).populate('studyGroups').exec((err, studyGroups) => { 
    if (err) { 
     return res.status(500).send(err); 
    } 
    study 
    return res.json({ studyGroups }); 
    }); 
} 

回答

1

现在可以使用$lookup

$lookup有四个参数

from做到在蒙戈3.2:指定在同一数据库中收集来执行与加盟。来自收藏集不能被分割。

localField:指定从文档输入到$ lookup阶段的字段。 $ lookup通过from集合的文档在localField上执行foreignField上的平等匹配。

foreignField:指定来自集合中文档的字段。

as:指定要添加到输入文档的新数组字段的名称。新的数组字段包含from集合中的匹配文档。

db.User.aggregate(
    {$unwind: "$bars"}, 
    {$lookup: { 
    from:"studyGroups", 
    localField: "studyGroups", 
    foreignField: "_id", 
    as: "studyGroupList" 

    }} 
) 
相关问题