Monday 5 June 2017

How to push ObjectID to MongoDB Schema array

I am trying to take the ID of a found user and append it to an array of "Participants" in my mongo schema. Whenever I try to do this, it never actually adds to the array in the schema.

My schema:

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

});

I have a function that finds users from usernames, and I want the found user to be added to the "Participants" array in the schema by their ID. This is what I have been trying:

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

What should I be doing differently to add the user's ID to the participants array of the schema?



via jblew

No comments:

Post a Comment