【问题标题】:Can't get mongoose/mongoDB to throw a 11000 (Duplicate Error)无法让 mongoose/mongoDB 抛出 11000(重复错误)
【发布时间】:2013-08-03 14:54:58
【问题描述】:

我肯定在这里遗漏了一些明显的东西。我的理解是下面的代码应该抛出一个 11000 Duplicate Key Error,但它只是将两个用户都添加到数据库中,并且不会抛出任何错误。任何人都知道如何使电子邮件独一无二?数据库版本 v2.4.5。

var mongoose = require('mongoose')
, Schema = mongoose.Schema;

mongoose.connect("mongodb://localhost/db");

var User = mongoose.model('User', new Schema({
    email: {type: String, index: true, unique: true}
}));

new User({
    email: "a@duplicate.com"
}).save(function(err,user){
    console.log(err);
});

new User({
    email: "a@duplicate.com"
}).save(function(err,user){
    console.log(err);
});

编辑

我似乎可以通过转到 mongo 命令行并输入:

db.users.ensureIndex({email:1},{unique:true});

节点脚本然后按预期正常工作并引发错误。但是,我不确定为什么这不适用于 Mongoose。 mongoose 调试的输出是:

Mongoose: users.ensureIndex({ email: 1 }) { safe: undefined, background: true, unique: true }
Mongoose: users.insert({ __v: 0, _id: ObjectId("51fb961445cf690000000001"), email: 'a@duplicate.com' }) {}
Mongoose: users.insert({ __v: 0, _id: ObjectId("51fb961445cf690000000002"), email: 'a@duplicate.com' }) {}
Err=null
Err=null

我注意到,如果我手动执行,输出中的 ensureIndex 行会失败。

【问题讨论】:

  • 原来有很多因素。在上面的示例中,如果我在确保索引和添加用户之间留出 1 秒的间隔,它将按预期工作。另一部分是确保集合中没有任何重复项。

标签: mongodb mongoose mongodb-query


【解决方案1】:

我的猜测是你的索引没有粘住,你后来修复了语法。

db.users.getIndexes()

下次使用它来验证集合上有索引。

【讨论】:

    猜你喜欢
    • 2015-06-11
    • 2021-02-11
    • 2017-01-03
    • 1970-01-01
    • 2018-10-12
    • 2015-05-01
    • 2020-07-11
    • 1970-01-01
    相关资源
    最近更新 更多