I want to update a document contains object in MongoDB. Since the updated object is given from the user, I don't know what exactly he was about to change.
For example I have this document in users collection:
{
_id: 1,
date: new Date(),
info: {
first_name: "a",
last_name: "b",
phone: "c"
}
}
The user is able to edit first_name and last_name but not phone.
This is the req.body (the input I receive from the user):
{
info: {
first_name: "aa"
}
}
Now in order to update only "info.first_name" and preserve the other fields that are stored in the info ojbect, I have to set an update query like this:
db.users.update({}, {$set: {"info.first_name": req.body.info.first_name}}, cb);
But the input is can be dynamic and changeable. I don't know if it's always be first name that was updated it can be last name or even other sub object like address: "info.address.city" (for example)
For that reason I handle those updates like this:
$set: req.body
And that is it. It works but I have an issue with this. It replaces the whole info ojbect and doesn't preserve other keys that were stored in it - phone is getting deleted and last name is getting deleted.
Is there a way to tell MongoDB to not replace the whole object but just update those keys that are mentioned?