【问题标题】:mongoose race condition causes errors猫鼬比赛条件导致错误
【发布时间】:2018-05-16 12:53:39
【问题描述】:

我正在我的客户端中实现最喜欢/不喜欢的功能,许多快速请求会导致错误的结果,可能是由于竞争条件。

会发生什么情况,该用户向最喜欢的帖子发送请求,然后很快取消收藏,但不喜欢的请求解决得更快,并导致Unhandled promise rejection (rejection id: 1): VersionError: No matching document found。所以我的问题是如何避免这种情况?是否有可能以某种方式确保最喜欢的问题首先得到解决?谢谢!

const UserSchema = new mongoose.Schema({
    favorites: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }]
})

UserSchema.methods.favorite = function(id) {
  if (this.favorites.indexOf(id) === -1) {
    this.favorites.push(id);
  }

  return this.save();
};

UserSchema.methods.unfavorite = function(id) {
  if (this.favorites.indexOf(id) > -1) {
    this.favorites.remove(id);
  }
    return this.save();
};

【问题讨论】:

  • 找到解决方案了吗?

标签: node.js mongodb mongoose


【解决方案1】:

您能否组合这些函数并包含一个else 以便它切换,而您只需要调用一个函数吗?例如:

UserSchema.methods.favorite = function(id) {
  if (this.favorites.indexOf(id) === -1) {
    this.favorites.push(id);
  } else {
    this.favorites.remove(id);
  }
  return this.save();
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 2017-06-15
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 2021-04-14
    相关资源
    最近更新 更多