Sushil
Sushil

Reputation: 2490

What is ensureIndex?

I'm a nodejs student and creating some practice project. I'm recently saw this on my console, when I run mongoose.set("debug", true).

What does it mean. Why it shows me an error like- duplicate key.

Mongoose: users.ensureIndex({ username: 1 }, 
 { unique: true, background: true })
Mongoose: posts.ensureIndex({ username: 1 }, 
 { unique: true, background: true })

How can I stop this to create like this and fix the error.

E11000 duplicate key error collection: cms_demo1.poosts index: username_1 dup key: 
{ : null }

need help.

Upvotes: 2

Views: 1105

Answers (1)

Rahul Kumar
Rahul Kumar

Reputation: 2831

So it looks like you are using index on username and that should be unique.

Every time you do a write operation, the mongo ensures that the index is respected.

Now the issue of duplicate key, looks like you have one document where username value is null, now the next time you are passing any other document with username as null, it invalidates the unique constraint, which means there could be only one document with username as null.

If you want to use unique index and also wants to allow null avlue for username for multiple documents, you can use sparse option with index.

You can drop the index and recreate it with sparse option

db.users.dropIndex({username : 1});
db.users.ensureIndex({ username: 1 }, 
 { unique: true, background: true, sparse : true })

I am guessing you have given the index definition through mongoose, in that case just update the definition there with sparse option.

More on sparse

Upvotes: 1

Related Questions