[Fixed] Username not changing properly using MongoDB update function?

Issue

Below is a snippet of my code where I begin by searching the collection of notes to see if any of them contain the username that I am changing my current session’s username to. If the username has not yet been used, it may be changed to that so I change the current session’s username and then I update every note to be under this new username then display a changesuccess.jade file. However, when I run the code everything appears to run fine exept the username for each note doesn’t change. I feel like it’s due to the find() method on the 5th line. Any help would be greatly appreciated!

router.post('/changeusername',function(req, res) {
    var newUsername = req.body.username;
    var user = req.session.username;

    var userFound = notesCollection.find( { owner: newUsername } )

    var results = function(infoInput) {
    res.render("changedUser.jade", {title: "Username Change",
                    info: infoInput});  
    }

    var checkChange = function(err) {
    if (err) {
        results("Username change failed!");
    } else {
        results("Username changed!");
    }
    }

    console.log(userFound);

    if (!userFound.length) {
        notesCollection.update({ owner: user }, 
                               { owner: newUsername}, 
                               { multi: true },
                               checkChange);
    } else {
        res.render("changedUser.jade", {title: "Username Change",
                                    info: "Username change failed!"});
    }
});

Solution

If i understand your problem correctly, you are trying to update a collection in mongodb and it is not getting updated.
So the problem is with the way you are calling mongoose#update.

Since you want to update ‘owner‘, you should use mongodb#$set

Mongoose supports the same $set operator in the conditions too.

So just a little correction for your case:

var conditions = { owner: user }
  , update = { $set: { owner: newUsername }}
  , options = { multi: true };

notesCollection.update(conditions, update, options, callback);

function callback (err, numAffected) {
  // numAffected is the number of updated documents
})

So try this now.

Leave a Reply

(*) Required, Your email will not be published