猫鼬竞争状况导致错误

时间:2017-12-02 16:27:44

标签: node.js mongodb mongoose

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

会发生什么情况,该用户向收藏的帖子发送请求,然后快速不受欢迎,但不受欢迎的请求会更快解决,并导致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();
};

1 个答案:

答案 0 :(得分:0)

你能组合这些功能并包含一个else以便它切换,你只需要调用一个函数吗? E.g:

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