Update in mongoDB is deleting the rest of the document

2

I have a Structured Collection like this:

{
  "_id": i43h21n5lk2354,
  "createdAt" : ISODate("2018-08-19T16:56:31.555Z"),
    "services" : {
            "facebook" : {
             ....
             name: "Michael Jackson"
             ....
             ....
}

I want to give the update in the name field, but it deletes all the rest of the document,

usersCollection.update(
 { _id: userId },
 {
  $set: {
    services: {
      facebook: {
        name: "Jackson Michael"
      }
    },
  }
})

After the update, and only thing that remains is the name field, all others disappear.

 {
  "_id": i43h21n5lk2354,
  "createdAt" : ISODate("2018-08-19T16:56:31.555Z"),
    "services" : {
            "facebook" : {
             name: "Jackson Michael"       
}
    
asked by anonymous 19.08.2018 / 19:07

1 answer

3

What happens is that you are asking Mongo to replace the entire contents of the sub-document services with:

facebook: {
    name: "Jackson Michael"
}

For this to happen, you must specify the field in your set like this:

usersCollection.update(
{ _id: userId },
{
    $set: {
        "services.facebook.name" : "Jackson Michael"
    }
})
    
19.08.2018 / 19:26