Update item in MongoDB

In an effort to make myself a better developer and destabilize my blood pressure, I'm learning Node.js. Lots of great tutorials out there, many thanks to the community. I'm reasonably good on my GETs, POSTs and DELETEs but I'm having an issue with doing a PUT request, specifically with how Mongo handles updating data. I'm new to noSQL and this is confusing me. Here's my controller code:

    router.put('/updateuser/:id', function(req, res){
        var db = req.db
        db.collection('userlist').updateById(req.params.id.toString(), {"username": req.body.username})
        console.log(req.params.id.toString())
    })

What I'm trying to do on line 3 here is to grab the proper item by the item id which comes through the url, then update the username with data from the http body. I've had some success but I'm not understanding how the update methods find what they are going to update, and every time I run the code I get a 500 back.

I call upon the gods of Mongo to shed light upon my ignorance, and tell me how I should be running an update command.

I'm not sure which db driver you're using but it looks like updating by _id. To match _id, you need to convert your id string to ObjectID. Note that you probably need to use $set to do the update ({$set: {"username": req.body.username}}). Here is the code:

var ObjectID = require('mongodb').ObjectID;

router.put('/updateuser/:id', function(req, res){
    var db = req.db
    db.collection('userlist').update({_id: ObjectID.createFromHexString(req.params.id)}, 
            {$set: {"username": req.body.username}}, function(err, updated) {
       if (updated) {
          console.log('updated');
       }
       console.log(req.params.id);  // don't need to do toString(), it's string
    })
});

Update: You're using udpateById() which I think it takes ObjectID.createFromHexString(req.params.id) instead of {_id: ObjectID.createFromHexString(req.params.id)} like update() does. But I believe they behave the same if you use {_id: ObjectID.createFromHexString(req.params.id)} in the update()