Gus
Gus

Reputation: 7505

Meteor.users collection not decreasing value on update

I'm calling a method: upvoteProject

'upvoteProject'(projectId){
    check(projectId, String);

    // Update project
    let projectById = Projects.findOne({_id: projectId});
    Projects.update({_id: projectId}, {$push: {backers: this.userId}, $inc: {totalBackers: 1}});

    // Register user votes for project
    const FIELDS = {
        availableVotes: 1,
        latestVoteAt: 1,
        canVoteAgainAt: 1,
    };
    let user = Meteor.users.findOne({_id: this.userId}, {fields: FIELDS});
    let $set = {}, $push = {}, $inc = {};

    if (user['availableVotes'] <= 1) {
        $set['canVoteAgainAt'] = getDatePlusTime({days: DATE_LIMIT});
        $push['projectsBacked'] = projectId;
    } else {
        $set['latestVoteAt'] = new Date();
        $inc['availableVotes'] = -1;
    }

    console.log($set, $push, $inc); // { latestVoteAt: Wed Jan 13 2016 18:40:37 GMT-0600 (CST) } {} { availableVotes: -1 }

    Meteor.users.update({_id: this.userId}, {$set: $set}, {$inc: $inc, $push: $push}, function(error, docs){
        console.log(error, docs); // null 1
    });

While Projects.update works great, I cannot make Meteor.users.update() decrease the value, however the document is indeed being affected (null 1).

I've tried by not using any $set, $push, $inc objects and instead doing setting the fields manually like this:

Meteor.users.update({_id: this.userId}, {$set: {fieldName: value} {//...}});

But no success either.

Other Meteor.users.update() methods are working though.

Upvotes: 0

Views: 117

Answers (1)

MrE
MrE

Reputation: 20768

Looking at the docs, http://docs.meteor.com/#/full/update I see you are applying multiple updates in separate objects:

it should be

Collection.update({ /query/ }, { /update object / }, [options], callback)

so try:

Meteor.users.update({_id: this.userId}, {$set: $set, $inc: $inc, $push: $push}, function(error, docs){
        console.log(error, docs); // null 1
    });

Upvotes: 1

Related Questions