MongoDB Update Single Field – Using document.update($set)

mongodbmongodb-3.0mongodb-3.2update

Can't seem to figure out how to update a single field.

Whatever I try, to update one field (picture: "url") the rest of the fields are being removed and set to null.

I use the following command now:

Meteor.users.update(
          userId,
          {
            $set: {
              profile: {
                picture: fileURL
              }
            }
          }
        );

And this is what happens with the rest of the object after update.

{
  "data": {
    "user": {
      "_id": "J222CqhR777GcXD",
      "createdAt": "Tue Sep 11 2018 19:23:55 GMT-0400 (EDT)",
      "email": "scott@example.com",
      "profile": {
        "about": null,
        "firstName": null,
        "lastName": null,
        "phone": null,
        "picture": "https://image.path/source.jpg"
      }
    }
  }
}

Is there another operator I am missing or some other way to do this?

In another document I am querying for all the data before, storing it in a React state and then passing all the fields that I have not changed to the update, but that seems rather inefficient and unnecessary step(???)

Is there really not a way to update just a single field without affecting the rest of the document?

cheers guys

Best Answer

Had to rewrite like so (profile.picture in one line with dot notation), this works:

Meteor.users.update(
    userId,
    {
        $set: {
            'profile.picture': fileURL
        }
    }
);

Answered by @coagmano on meteor forums