【问题标题】:Mongoose - caused by :: 11000 E11000 duplicate key error index?Mongoose - 由 :: 11000 E11000 重复键错误索引引起?
【发布时间】:2017-01-03 17:33:43
【问题描述】:

为什么我会收到此重复错误 - Error creating new user: WriteError({"code":11000,"index":0,"errmsg":"insertDocument :: caused by :: 11000 E11000 duplicate key error index?

所有提供的字段都不为空。

架构:

// Declare schema
var userSchema = new mongoose.Schema({
    username: {type: String, required: true, index: {unique: true}},
    password: {type: String, required: true},
    created_on: {type: Date, default: Date.now}
});

帖子:

// Create - POST
// Create the first method of the API : POST used to create a new user.
router.post("/", function(req, res, next) {
    // Get values from POST request
    var username = req.body.username;
    var password = req.body.password;
    console.log(req.body); // { username: 'tealou', password: 'test123' }

    // Create new user document
    User.create({
        username: username,
        password: password
    }, function(err, user) {
        console.log(user); // undefined
        if (err) {
            console.log("Error creating new user: " + err);
            res.send("Error creating new user.");
        } else {
            console.log("POST creating new user: " + username);
            res.json(user);
        }
    })
});

错误:

创建新用户时出错: WriteError({"code":11000,"index":0,"errmsg":"insertDocument :: 导致 by :: 11000 E11000 重复键错误索引:iotdb.users.$name_1 dup 键:{:空 }","op":{"username":"tealou","password":"$2a$10$7mPGND2FRuJDGnXaVTnkru2.xsGn2Ksf8veBKur4ouD9VUNj60RaC","_id":"5786020088245d33140d6f94","created_on":"2016-07-13T05: :28.279Z","__v":0}})

有什么想法吗?

【问题讨论】:

  • 这听起来有点明显,但数据库中是否还有其他用户名为tealou 的用户?
  • 有所有可用的数据和相同的数据..

标签: node.js mongodb express mongoose


【解决方案1】:

删除集合并允许我的代码重新创建它,这对我有用。

【讨论】:

    【解决方案2】:

    您的架构中最初有一个名为 name 的字段,该字段设置为 unique。

    我怎么知道?因为错误告诉我:

    duplicate key error index: **iotdb.users.$name_1**
    

    您将该字段重命名为 username,但没有删除旧索引。默认情况下,MongoDB 会将不存在的字段的值设置为null。

    相关文档here:

    如果文档在唯一索引中没有索引字段的值,则索引将存储该文档的空值。由于唯一性约束,MongoDB 将只允许一个缺少索引字段的文档。

    要解决这个问题,您需要删除重命名的name 字段的索引。

    【讨论】:

    • 你是对的。我手动删除了 db.users.dropIndex({"name":1}) 并再次运行该帖子,然后它就像一个魅力!
    • 老兄。简直太棒了:)
    • 那是福尔摩斯级别的调试
    • @Seinfeld 从 mongo shell (docs.mongodb.com/manual/reference/method/…) 运行 db.collection.dropIndex()
    猜你喜欢
    • 2017-05-25
    • 2016-10-31
    • 2018-01-19
    相关资源
    最近更新 更多