R
R
razer962019-02-07 16:52:35
MongoDB
razer96, 2019-02-07 16:52:35

How to merge objects in a document on update in Mongoose?

Hi all. There is a document update task in MongoDB.
Suppose I have a document in the database that looks like this:

{
   "phone": "+7********",
   "profile: {
       "username": "Username",
    }
}

And from the client I receive an object:
{
   "profile": {
        "firstname": "My name"
    }
}

How to make it so that when updating the profile object is not overwritten, but objects are merged? For example, if there is no firstname parameter in the object, then it would simply be added, and if it exists, then it would be updated.
My code so far is this:
User.findOneAndUpdate(id, {$set: {profile: data.profile}}, {new: true}, (err, updatedUser) =>{
....
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question