Mongoose's unique validation error, although there is no single restriction

var schema = new Schema({

    _id: Schema.ObjectId,
    email: {type: String, required: true}

});

Previously, the emailfield was unique (with a unique constraint). Now I removed the unique constraint, and then it gave a unique validation error. I restarted mongo and then it threw an error. Any idea?

+4
source share
1 answer

When you delete a unique constraint in a schema definition, you had to manually remove it from the database. You can do this either in the mongo shell using a method , or in an application using your own node.js collection method. dropIndex() dropIndex()

, , ; , , , Mongoose.

mongo, , users test:

> db.users.getIndexes()

, :

[
    {
            "v" : 1,
            "key" : {
                    "_id" : 1
            },
            "name" : "_id_",
            "ns" : "test.users"
    },
    {
            "v" : 1,
            "unique" : true,
            "key" : {
                    "email" : 1
            },
            "name" : "email_1",
            "ns" : "test.users",
            "background" : true,
            "safe" : null
    }
]

, , Mongoose User, , getIndexes() node.js :

User.collection.getIndexes(function (err, results) {
    // Handle errors
});

mongo dropIndex():

> db.users.dropIndex("email_1")

Mongoose node.js dropIndex() :

User.collection.dropIndex("email_1", function (err, results) {
    // Handle errors
});
+6

Source: https://habr.com/ru/post/1625116/


All Articles