Update on mongoDB is deleting the rest of the document

Asked

Viewed 69 times

2

I have a collection structured like this:

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

I want to update the field name, but it erases all the rest of the document, I’m using so:

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

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

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

1 answer

3


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

facebook: {
    name: "Jackson Michael"
}

For this not to happen you must specify the field in your set in this way:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.