This is my mongoosejs schema. I set name unique to false, but this is what i get: MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: testdb1.images.$name_1 dup key: { : "aaa" }
imageSchema = new Schema({
url: {
type: String,
unique: true,
required: true
},
category: {
type: String,
required: true
},
vote: {
type: Number,
required: true
},
name: {
type: String,
unique: false,
required: true
},
voteArray: [],
favorite: false,
tags: []
});
any ides how to solve this ? suggestions ?
1. Duplicate documents already created in DB before defining this property You might have already added some duplicate data in the database so mongoose and MongoDB simply doesn't check unique field because it's already messed up Delete the messed data from the MongoDB collections page to solve it 2.
One workaround is to make the email property required, which disallows null and undefined: If you need email to be unique unless it is not defined, you can instead define a sparse unique index on email as shown below. To make MongoDB E11000 error messages user-friendly, you should use the mongoose-beautiful-unique-validation plugin.
When writing Mongoose tests, we normally recommend using deleteMany () to clear out data in between tests, rather than dropDatabase (). This ensures that you delete all documents, without clearing out database-level configuration, like indexes and collations. deleteMany () is also much faster than dropDatabase ().
Mongoose won't modify existing indexes, so you'll need to drop that index in the MongoDB shell and then let Mongoose recreate it using the definition in your schema:
> db.images.dropIndex('name_1');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With