MongoDB重复条目

时间:2015-12-23 16:15:14

标签: mongodb

我有以下架构

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。延迟是否会成为一个大问题?

1 个答案:

答案 0 :(得分:1)

很可能有这种行为:

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/

根据您的需要,您还可以拥有" upsert"更新或插入新记录。在您的情况下,如果您担心两个用户创建具有相同ID的新用户,只需在数据库上放置一个索引。

相关问题