最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - decrement value in collection until 0 - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Aug 3, 2015 at 13:03 DudeDude 1,0452 gold badges15 silver badges37 bronze badges 1
  • In Mongoose v4 you can define a minimum Number. Take a loot at: mongoosejs.com/docs/schematypes.html – Thomas Bormans Commented Aug 3, 2015 at 13:32
Add a comment  | 

3 Answers 3

Reset to default 19
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
  }
});
发布评论

评论列表(0)

  1. 暂无评论