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

lau*_*kok 10 mongoose mongodb node.js express

为什么我会收到此重复错误 - 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}
});
Run Code Online (Sandbox Code Playgroud)

帖子:

// 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);
        }
    })
});
Run Code Online (Sandbox Code Playgroud)

错误:

创建新用户时出错:WriteError({"code":11000,"index":0,"errmsg":"insertDocument ::由:: 11000引起E11000重复键错误索引: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}})

有任何想法吗?

rob*_*lep 26

您最初name在架构中调用了一个字段,该字段已设置为unique.

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

duplicate key error index: **iotdb.users.$name_1**
Run Code Online (Sandbox Code Playgroud)

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

相关文档在这里:

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

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


Jan*_*ena 5

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