Search code examples
node.jsmongodbmongoosemongodb-update

How to update object in mongoose


I have a schema that looks like this:

var userSchema = mongoose.Schema({
    facebook         : {
        id           : String,
        token        : String,
        email        : String,
        name         : String
    },
    twitter          : {
        id           : String,
        token        : String,
        displayName  : String,
        username     : String
    },
    google           : {
        id           : String,
        token        : String,
        refreshToken : String,
        email        : String,
        name         : String
    },
    slack            : {
        id           : String,
        token        : String,
        teamId       : String,
        name         : String
    }

});

And i want to update google's access token given the refreshToken. How can i achieve that?

I tried this but it doesnt seem to work

       UserModel.update(
                { 'google.refreshToken': refreshToken },
                {token: 'asdf'},
                {multi: false},
                function (err, raw) {
                    if (err) {
                        console.log('Error log: ' + err)
                    } else {
                        console.log("Token updated: " + raw);
                    }
                }
        );

Solution

  • I think you've got it the other way round:

    UserModel.update(
        { "google.refreshToken": refreshToken },
        { "$set": { "google.token": "asdf" } },
        function (err, raw) {
            if (err) {
                console.log('Error log: ' + err)
            } else {
                console.log("Token updated: " + raw);
            }
        }
    );