Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose unique validation error even though unique constraint is not there

var schema = new Schema({

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

});

Previously email field was unique (with unique constraint) Now I removed unique constraint, then also it's giving unique validation error. I have restarted mongo then also it's throwing error. Any Idea?

like image 425
Jagajit Prusty Avatar asked Feb 08 '23 23:02

Jagajit Prusty


1 Answers

When you remove the unique constraint in the schema definition, you were supposed to manually remove it from the database as well. You can do this either in mongo shell by using the dropIndex() method or in your application using the native node.js driver's dropIndex() method of the collection.

You may need to confirm this first by checking the indexes currently in the database; you will most probably find the email unique index created when you populated the collection after defining the schema in Mongoose.

You can issue the command in mongo shell, supposing you have a collection named users in your database named test:

> db.users.getIndexes()

which will show the current indexes, you may see in your console an array like the following:

[
    {
            "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
    }
]

For a solution in your application code, supposing you have a Mongoose model called User that has the defined schema above, you can call the getIndexes() native node.js driver's collection method:

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

In mongo shell, you can then go ahead and remove the email index with the dropIndex() method :

> db.users.dropIndex("email_1")

In your application code, you can also issue the command via the Mongoose model for the collection, and call the native node.js driver's dropIndex() method of the collection:

User.collection.dropIndex("email_1", function (err, results) {
    // Handle errors
});
like image 156
chridam Avatar answered Feb 11 '23 03:02

chridam