mongoose赛跑情况导致错误

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

会发生什么事,那个用户发送一个请求到最喜欢的post,然后,非常不合适,但不正确的请求解决更快,并导致Unhandled promise rejection (rejection id: 1): VersionError: No matching document found 。 所以我的问题是如何避免这种情况? 是否有可能确保最喜欢的解决scheme? 谢谢!

 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(); }; 

你可以结合function,并包括一个else所以它切换,你只需要调用一个函数? 例如:

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