【问题标题】:Mongo DB increment if statement (Meteor App)Mongodb增量if语句(Meteor App)
【发布时间】:2014-12-31 06:56:32
【问题描述】:

我似乎无法解决这个看似简单的问题。

下面的代码允许我在我的帖子对象上将喜欢的数量加或减 1。

我希望能够做到以下几点:

如果 postLikes = 0 则停止允许我减少喜欢的次数。

我不想将喜欢的次数减少到 0 以上。

这是我的代码:

Template.post.events({
  "click .likeButton": function() {
    // Set the checked property to the opposite of its current value
    Posts.update(this._id, {
      $inc: {
        postLikes: 1
      }
    });
  },
  "click .dislikeButton": function() {

    // Set the checked property to the opposite of its current value

    Posts.update(this._id, {
      $inc: {
        postLikes: -1
      }
    });
  }
});

【问题讨论】:

    标签: javascript mongodb meteor handlebars.js


    【解决方案1】:

    那么,在你更新之前有一个条件呢?

    更新 - 没关系。更好的方法是通过查询!

    "click .dislikeButton": function() {
        Posts.update({_id : this._id, postLikes : {$gt : 0}}, {
          $inc: {
            postLikes: -1
          }
        });
    }
    

    【讨论】:

    • 发挥了绝对的魅力。谢谢!
    • 这是一种愚蠢的方式来实现这一点。 update 的第一个参数是一个选择器,您可以在其中指定限制更新的条件。它接受{_id:this._id, postLikes:{$gt: 0}} 并且如果条件不符合则不会更新文档。
    【解决方案2】:

    您的修饰符只有在文档匹配“update”的第一个参数(选择器)中的条件时才会被应用。我看到了接受的答案,但实际上只使用一个 db 调用并让 db 在可能的情况下检查对象标准。像这样:

    "click .dislikeButton": function() {
      Posts.update({ _id: this._id, postLikes:{ $gt: 0 }}, { $inc: { postLikes: -1 }});
    }
    

    documentation on Mongo updateMeteor's update

    【讨论】:

      猜你喜欢
      • 2015-02-14
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多