Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PATCH method to MongoDB using Node

I want to create a PATCH method for my API but there is something I don't understand. Imagine I have the following document in my MongoDB database:

{
    _id  : ObjectId(1234...),
    name : "bob",
    age  : 30
}

Now I would like to update this document but I don't know what keys my API will receive. So imagine I make a request in order to change the age but also add a last_name.

The request result would be like this:

{
    _id  : ObjectId(1234...),
    name : "bob",
    last_name : "smith",
    age  : 44
}

The main problem here is that I don't know the arguments I will receive.

My goal is to update the values of the existing keys and add the keys that are not in the document.

Any idea?

Thanks

like image 391
marc_aragones Avatar asked Mar 03 '15 19:03

marc_aragones


1 Answers

You want to use the $set operator.

What this does is only updates the keys that are sent in the update query. Without $set, it will overwrite the whole object, which is obviously not what you want.

app.patch('/user/:id', function (req, res) {
    var updateObject = req.body; // {last_name : "smith", age: 44}
    var id = req.params.id;
    db.users.update({_id  : ObjectId(id)}, {$set: updateObject});
});

I'm assuming a couple things here:

  1. You are using express.
  2. You are using either the mongodb driver or mongojs npm module
like image 104
Brian Noah Avatar answered Oct 21 '22 11:10

Brian Noah