Search code examples
meteormeteor-accounts

How to update the content of Meteor.user().profile attributes?


I have a button that supposed to decrease an attribute inside the user if it is pressed,

I want to decrease the annualLeave attribute when its pressed.

"profile" : {
        "annualLeave" : 14,
        "replancementLeave" : 0,
        "medicalLeave" : 7
    }
}

Here is my code to get the userID:

Session.set('getUserId', Al.findOne({_id: Session.get('appealId')}));
console.log(Session.get('getUserId').userID);

The appealId session has the _Id of the current item. inside the item the _Id of the user, in which the item belongs to is stored in userID.

After I get the userID, I use it to retrieve the annualLeave. Here is the code:

Session.set('userDetails', Meteor.users.findOne({_id: Session.get('getUserId').userID}));
console.log(Session.get('userDetails').profile.annualLeave);

until now, both console.log prints out the values successfully.

Now to final step, I want to decrease the annualLeave by 1 and then update the user information in the database,

here is my code (doesn't work):

Session.set('counter', Session.get('userDetails').profile.annualLeave - 1);
Meteor.users.findOne({_id : Session.get('getUserId').userID},{$set:{profile.annualLeave: Session.get('counter')}});

What am I doing wrong the last part?


Solution

  • You need to put the key in quotes if it's not at root level and you need to use the .update() method instead of .findOne()

    Meteor.users.update(Session.get('getUserId').userID,
      { $set: { "profile.annualLeave": Session.get('counter') }});
    

    You can also skip part of your use of Session by just decrementing the value:

    Meteor.users.update(Session.get('getUserId').userID,
      { $inc: { "profile.annualLeave": -1 }});
    

    Note that if you're only searching by _id you can just pass the value as the first parameter instead of an object.