Sunday, 4 June 2017

How to use "current user" in node.js project?

I'm working on a real-time colloboration project using node.js and express. Users will be able to create "Groups" - places where they can work with others. So far, I have the group creation functionality made, but I would like to set the "owner" (or "creator") of the group as the currently logged in user. How exactly would I go about grabbing the ID of the logged in user when they are creating a group and setting it to the 'Owner' field within the Schema? Here is my code..

Group MongoDB Schema:

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

POST method for Creating a Group:

// Create Group POST
router.post('/creategroup', function(req, res){

    var name = req.body.groupname;
    var subject = req.body.groupsubject;

    req.checkBody('groupname', "A group name is required").notEmpty();

    var errors = req.validationErrors();

    if(errors) {
        res.render('creategroup', {
            errors:errors
        });
    }
    else {
        var newGroup = new Group({
            name: name,
            subject: subject, 
            owner: ???
        });

        Group.createGroup(newGroup, function(err, group){
            if(err) throw err;
            console.log(name);
        });

        req.flash('success_msg', "You have started a new group! Get working!");

        res.redirect('/');
    }
});

Thanks for the help!



via jblew

No comments:

Post a Comment