Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Why do I get this duplicate error - Error creating new user: WriteError({"code":11000,"index":0,"errmsg":"insertDocument :: caused by :: 11000 E11000 duplicate key error index?

All the provided fields are not empty at all.

Schema:

// 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}
});

Post:

// 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);
        }
    })
});

Error:

Error creating new 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}})

any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
726 views
Welcome To Ask or Share your Answers For Others

1 Answer

You initially had a field called name in your schema, that was set to unique.

How do I know? Because of the error telling me so:

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

You renamed the field to username, but didn't remove the old index. By default, MongoDB will set the value of a non-existent field to null in that case.

Relevant documentation here:

If a document does not have a value for the indexed field in a unique index, the index will store a null value for this document. Because of the unique constraint, MongoDB will only permit one document that lacks the indexed field.

To solve this, you need to remove the index for the renamed name field.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...