Mongoose - 由于:: 11000 E11000重复键错误索引引起的问题?

10

我为什么会遇到这个重复错误 - 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 :: caused by :: 11000 E11000 duplicate key error index: iotdb.users.$name_1 dup key: { : null }","op":{"username":"tealou","password":"$2a$10$7mPGND2FRuJDGnXaVTnkru2.xsGn2Ksf8veBKur4ouD9VUNj60RaC","_id":"5786020088245d33140d6f94","created_on":"2016-07-13T08:55:28.279Z","__v":0}})

有什么想法吗?


1
这可能听起来有点显而易见,但是数据库中是否有其他用户名为tealou的用户? - connorb
已经有相同的数据可用。 - sandeep rawat
2个回答

31

最初在您的模式中有一个名为 name 的字段,它被设置为 unique

我是如何知道这一点的呢?因为错误告诉了我:

duplicate key error index: **iotdb.users.$name_1**
您将字段重命名为username,但未删除旧索引。在这种情况下,默认情况下MongoDB将把不存在的字段的值设置为null
相关文档在此处

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

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

你是对的。我手动删除了 db.users.dropIndex({"name":1}) 并重新运行了该帖子,现在它像魔法般地工作了! - Run
老兄,真是太棒了 :) - shikhar bansal
那是一些夏洛克·福尔摩斯级别的调试。 - Janac Meena
@Seinfeld 从mongo shell运行db.collection.dropIndex()(https://docs.mongodb.com/manual/reference/method/db.collection.dropIndex/)。 - robertklep

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接