2017-12-02 124 views
1

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

会发生什么,该用户发送一个请求到最喜欢的帖子,然后,非常不满意,但不公平的请求解决更快,并导致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(); 
}; 

回答

0

你能不能结合的功能,包括一个else,使其切换,你永远只需要调用一个函数?例如:

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