首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MongoDB重复条目

问MongoDB重复条目
EN

Stack Overflow用户
提问于 2015-12-23 16:15:14
回答 1查看 49关注 0票数 0

我有以下模式

代码语言:javascript
复制
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。延迟会带来大问题吗?

EN

回答 1

Stack Overflow用户

发布于 2015-12-23 17:25:55

有这种行为是很有可能的:

代码语言:javascript
复制
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的新用户,只需在数据库中添加一个索引即可。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34439704

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档