Dud*_*ude 1 javascript mongodb meteor
我正在使用meteorJS并且user collection在用户配置文件中存储了一个名为"score"的值.
现在,我希望每个用户的分数值减少10更新集合,但是我在获取每个用户的分数值时遇到问题并更新它们"current value - 10".它也应该只更新不会低于0的值.
有人可以给我一个提示如何查找和更新每个用户的配置文件的值吗?
Meteor.users.update({'profile.score': {$gte: 10}}, {$inc: {'profile.score': -10}}, {multi: true});
Run Code Online (Sandbox Code Playgroud)
这是否能满足您的需求?根据需要更改选择器.
说明:我们筛选出分数为10或更高的用户.我们将所有匹配用户的得分"增加"-10(因此我们将它们减少10).
这里的基本过程是使用更新运算符,但当然还有作为下限值$inc的治理。0因此,您可以接受:
Users.update({ "_id": userId },{ "$inc": { "score": -10 } });
Users.update(
{ "_id": userId, "score": { "$lt": 0 } },
{ "$set": { "score": 0 } }
);
Run Code Online (Sandbox Code Playgroud)
如“二”的操作和连接如图所示。或者,您可以使用MongoDB 的批量操作 API来更喜欢 Meteor 方法:
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
}
)
);
}
);
Run Code Online (Sandbox Code Playgroud)
“服务器”请求的优点在于,尽管仍然是“两个”更新操作,但来自服务器的实际请求和响应只是“一个”请求和“一个”响应。所以这比两次往返的效率要高很多。特别是如果从浏览器客户端启动。
如果您不这样做,那么您可能会错过一些事情,例如当前值为 ,6并且您希望将其减少到0。$gt条件中的A将会失败。