I recognized this question has been asked before, but none of the solutions seemed to work for me.
I have a simple model I'm defining like this:
const mongoose = require('mongoose')
const { Schema } = mongoose
let subscriberSchema = new Schema({
firstName: { type: String, required: true },
email: { type: String, required: true, unique: true }
}, { timestamps: true })
let Subscriber = mongoose.model('Subscriber', subscriberSchema)
If I run the following (in the REPL, so no async issues), I'd expect to see an error being logged for the second call to create
.
Subscriber.create({ firstName: "Landon", email: "example@example.com" })
Subscriber.create({ firstName: "Landon", email: "example@example.com" }, function(err) {
console.log("ERROR", err)
})
Instead, I see "ERROR" null
.
If I run a count
query or a find
query, I can see both models were created. What am I doing wrong?
Edit
Here are a few of the things I've already tried:
- Restart MongoDB after adding index
- Removing all of the existing records so there are no existing records that could violate the uniqueness constraint
- Defining the
email
attribute all of these ways (I've seen different implementations in different places):{ type: String, required: true, unique: true }
,{ type: String, required: true, index: true, unique: true }
,{ type: String, required: true, index: { unique: true } }
.