1
votes

I've searched the internet extensively, and no one seems to have an answer for this problem. I have a Mongoose Schema tied to a DB in Mongo. I want to create a unique index on the email field of my User document. The code below should work, as far as I can tell from the limited documentation I could find. Can anyone tell me why it fails, and allows me to create users with duplicate emails?

var userSchema = new Schema({
    email: { type: String, required: true, index: { unique: true, trim: true } },
    password: String,
    firstName: String,
    lastName: String
 }, { autoIndex: true });
1
can you get into mongodb on the command line using mongo and check what the index (if it exists) looks like and add it to your question? - John Petrone

1 Answers

0
votes

That trim probably shouldn't be there: it's a setting for strings, not for indexes. Try the following:

var userSchema = new Schema({
    email: { 
        type: String,
        trim: true,
        required: true,
        unique: true
    },
    password: String,
    firstName: String,
    lastName: String
}, { autoIndex: true });