Search code examples
node.jsmongodbmongoose

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?


Solution

  • 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