I´m using meteorJS
and have a user collection
where I´ve stored a value called 'score' in the users profile.
Now, I want to update the collection with a decrement of the score value by 10 for each user but I have problems with getting the score value for each user and update them like "current value - 10"
. It also should only update the values that will not become lower than 0.
Can someone give me a hint how to find and update the value for each user the profile?
Meteor.users.update({'profile.score': {$gte: 10}}, {$inc: {'profile.score': -10}}, {multi: true});
Does this accomplish what you need? Change selector as needed.
Explanation: We filter out users who have a score of 10 or more. We "increase" all of the matching users' scores by -10 (so we decrease them by 10).
The basic process here is to use the $inc
update operator, but of course there is the governance of 0
as a floor value. So you can therefore either accept:
Users.update({ "_id": userId },{ "$inc": { "score": -10 } });
Users.update(
{ "_id": userId, "score": { "$lt": 0 } },
{ "$set": { "score": 0 } }
);
As "two" operations and connections as shown. Or you can get fancier in Meteor methods with the Bulk Operations API of MongoDB:
Meteor.methods(
"alterUserScore": function(userId,amount) {
var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;
var bulk = db.collection('users').inititializeOrderedBulkOp();
bulk.find({ "_id": userId }).updateOne({ "$inc": { "score": amount } });
bulk.find({ "_id": userId, "score": { "$lt": 0 } }).updateOne({
"$set": { "score": 0 }
});
bulk.execute(
Meteor.bindEnvironment(
function(err,result) {
// maybe do something here
},
function(error) {
// report real bad here
}
)
);
}
);
The advantage there on the "server" request is that even though it is still "two" update operations, the actual request and response from the server is only "one" request and "one" response. So this is a lot more efficient than two round trips. Especially if intitiated from the browser client.
If you did otherwise, then you likely miss things such as when the current value is 6
and you want to decrease that to 0
. A $gt
in the condition will fail there.
You can try this as the Schema instead.
const Customer = new Schema({
cash: {
type: Number,
min: 0
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With