如何将ObjectID推送到MongoDB Schema数组

时间:2017-06-06 00:38:18

标签: node.js mongodb express

我正在尝试获取已找到用户的ID,并将其附加到我的mongo架构中的“Participants”数组中。每当我尝试这样做时,它实际上都不会在模式中添加到数组中。

我的架构:

// Group Schema
var GroupSchema = new Schema({
    name: String,
    subject: String,
    owner: { type: Schema.Types.ObjectId,
                    ref: 'User' }, 
    participants: [{ type: Schema.Types.ObjectId,
                    ref: 'User' }],

});

我有一个从用户名中查找用户的函数,我希望找到的用户可以通过ID添加到架构中的“Participants”数组中。这就是我一直在尝试的:

...
if(errors) {
        res.render('creategroup', {
            errors:errors
        });
    }
    else {
        var addUser = req.body.addUser;

        User.getUserByUsername(addUser, function(err, user){
            if(err) throw err;
            if(!user){
                console.log("There's no user with that username");
            }
            else{
                res.redirect('/users/dashboard');
                console.log("A user was found!");
                var id = user.id;

                array.push(id);


            }
        });

        var name = req.body.groupname;
        var subject = req.body.groupsubject;
        var owner = req.user.id;
        var array = [];

        var newGroup = new Group({
            name: name,
            subject: subject, 
            owner: owner,
            participants: array,
        });

我应该以不同的方式将用户的ID添加到架构的参与者数组中?

0 个答案:

没有答案