【问题标题】:Increment with constraints? Mongodb增加约束?蒙古数据库
【发布时间】:2015-11-04 01:48:27
【问题描述】:

我有一个生命值变量,当玩家受到伤害或被治愈时,它需要增加或减少生命值。

默认的解决方案是只做一个查找,减去或添加到健康然后设置。但这不会是原子的,并且在 find 和 set 之间可能会请求损坏或修复,从而导致值错误。

因此,要以原子方式执行此操作,使用 inc 运算符查找和更新/修改可能会起作用,除非您不能损坏底片或治愈超过最大值。所以我需要一种方法来限制增量。可能吗?

我想到的唯一其他解决方案是使用推拉操作符在阵列中排队治疗和损坏,但我担心阵列快速增长会出现性能问题,我需要不断汇总它以获得当前的健康状况。

【问题讨论】:

    标签: node.js mongodb mongodb-query


    【解决方案1】:

    您可以尝试使用 Update If Current 模式来解决并发问题。

    http://docs.mongodb.org/manual/tutorial/update-if-current/

    基本上,您是在进行更新调用,但要应用更新的文档的查询包括您要更新的旧值。类似于以下内容:

    function damagePlayer(username, done) {
      var player = db.players.findOne( { username: username } );
    
      if ( player ) {
         var oldHealth = myDocument.health;
         var health = oldHealth - 1;
         if(health < 0) {
           health = 0;
         }
    
         var results = db.products.update({
            _id: player._id,
            health: oldHealth
          },{
            $set: { health: health }
          });
    
         if ( results.hasWriteError() ) {
            // This probably means that the health was updated while we were 
            // fetching the data to update. Just need to run this process 
            // again to re-apply the update.
            return process.nextTick(damagePlayer.bind(this, username, done));
         }
    
         done();
      }
    }
    

    【讨论】:

    • 这看起来很有希望!谢谢。我唯一关心的是某种无限递归循环,所以我可能会在这里添加一个计数......
    猜你喜欢
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 2017-02-12
    相关资源
    最近更新 更多