[SOLVED] Update one field of Meteor.user


#1

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


#2

You are resetting the entire profile object in your mongo query. It does not just update the one property. You are inherently saying replace the entire object.

You need to rewrite the set part with “profile.pictureUrl”=url to only set a particular property. Quote are required off the top of my head.


#3

As @pmcochrane said, you will need to rewrite your query

Mongo lets you set deep properties with a string key using dot notation like so:

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

#4

@coagmano & @pmcochrane much love, dear sirs! Solved!