【发布时间】: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();
};
【问题讨论】:
-
找到解决方案了吗?