For example if I have this schema
var userSchema = mongoose.Schema({
username: String,
email: String,
password
I came across the same issue. But can't be solved by the accepted answer.
For my example is very simple, just make the name
unique.
var FoolSchema = Schema({
name: {
type: String,
unique: true,
index: true,
required: true
}
})
I can save the duplicate name every time.
Then I find this link: https://mongoosejs.com/docs/faq.html#unique-doesnt-work
The solution is createIndex
from mongoDB
, not from mongoose.
mongo
, and use yourdbName
db.foos.getIndexes()
(you can't see the "unique" : true,
)db.foos.createIndex( { "name": 1 }, { unique: true } )
unique
.Hope it could help someone.
EDIT
If your foo
table collections contain the duplicated names, you might get error on step 3:
{
"ok" : 0,
"errmsg" : "E11000 duplicate key error collection: mategoal-dev.categories index: name_1 dup key: { : \"TheName\" }",
"code" : 11000,
"codeName" : "DuplicateKey"
}
Then remove all the data or duplicated one(haven't test) first:
db.foos.remove({})
Then try step 3 again.
You can add a constraint with the unique
attribute. This will also add a "unique" index for the field to your collection:
var userSchema = mongoose.Schema({
username: { type: String, unique: true },
email: String,
password: String,
_todo: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Todo'}]
});