2017-02-21 176 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" 

    }} 
) 
相關問題