我有以下模式
var customerSchema = new Schema({
customerID: String,
phoneNumber: String
})
customerSchema.path('customerID').validate(function (customerID, next) {
Customer.findOne({customerID: customerID}, function (err, user) {
if (err) {
return next(false);
}
if (!user) {
return next(true); //Valid
} else {
return next(false);
}
});
}, 'customerID Already Exists');当我试图添加相同的customerID时,这个功能非常好。它不会让我。但在此之前,我尝试在上按下ADD按钮,在不同的计算机上按相同的时间。不知何故,添加了相同的customerID。
如何防止这种边缘情况的发生?我正在使用MongoLab。延迟会带来大问题吗?
发布于 2015-12-23 17:25:55
有这种行为是很有可能的:
Press add button on computer1
Press add button on computer2
Validation occurs for the first add and the customer does not exist
Validation occurs for the second add BEFORE the first insert is done and the customer does not yet exist
Both adds succeed可以在数据库级别上对字段设置唯一约束,以防止出现这种情况- https://docs.mongodb.org/v3.0/tutorial/create-a-unique-index/。
根据您的需要,您还可以有一个更新或插入新记录的“向上插入”。在您的示例中,如果您关注两个用户创建具有相同ID的新用户,只需在数据库中添加一个索引即可。
https://stackoverflow.com/questions/34439704
复制相似问题