Mongo DB 增量 if 语句(Meteor App)

Mongo DB increment if statement (Meteor App)

本文关键字:Meteor App 语句 DB 增量 if Mongo      更新时间:2023-09-26

我似乎无法绕过这个看似简单的问题。

下面的代码允许我在帖子对象上将喜欢的数量加减 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
      }
    });
  }
});

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

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

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

仅当文档与选择器"update"的第一个参数中的条件匹配,才会应用修饰符。 我看到了接受的答案,但实际上只使用一个数据库调用,并在可能的情况下让数据库检查对象条件。 喜欢这个:

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

请参阅有关Mongo更新和Meteor更新的文档。