1

I am trying to make email field as unique on database level. When a new document is created with same emailId it should throw an error. To implement it I am using email : {type: String, trim: true, index: true, unique: true, sparse: true,required: true}

But it doesn't seem to be working , currently it is adding new documents with same emailId.

Referred this post : mongoDB/mongoose: unique if not null

Checked .getIndexes() and this is the output of it :

enter image description here

Lovika
  • 577
  • 2
  • 10
  • 21
  • 1
    You have unneeded options there that cancel each other out. If you mean `"unique"` then you don't need or want `sparse` or `required`, which are conflicting and implied respectively. If there is no index there then there is probably an error because the data does not meet the "unique" constraint. Go in the the shell, check the indexes with `.getIndexes()` on the collection and then try to create the index with `.createIndex()` if it's not there, and you should see the error. Post current indexes and/or error if you still don't understand. – Neil Lunn Nov 01 '17 at 21:51
  • I don't have much idea of mongoDb but I removed `sparse` and `required` but still getting the same output. checked the indexes with `.getIndexes()` have added the output of that in the question itself – Lovika Nov 02 '17 at 00:04
  • 1
    I also asked you to attempt to `.createIndex({ "email": 1 }, { "unique": true })`. Setting options on the mongoose schema will not fix this at this point. You to to attempt to create the index from the "shell" ( please because we want "text" and not screenshots ) and see what the error is reported at. It's going to tell you the index creation failed, and it's going to tell you "exactly why" and which data is presently causing the problem. – Neil Lunn Nov 02 '17 at 00:15
  • Got it. Tried command `.createIndex()` and got this error `E11000 duplicate key error collection: diesel-local.admins index: email_1 dup key: { : \"admin@admin.com\" }` – Lovika Nov 02 '17 at 00:18
  • 1
    Yes so now you see you have "duplicate" information in `"email". You need to "remove your duplicates" before you can create a "unique" index. Understand now? – Neil Lunn Nov 02 '17 at 00:19
  • Got it. It's working now thanks – Lovika Nov 02 '17 at 00:24

1 Answers1

9

you can use mongoose-unique-validator

const mongoose = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator')
const Schema = mongoose.Schema

const UserSchema = new Schema({
  email: {
       type: String,
       required: true,
       unique: true
  },
  username: {
    type: String,
    required: true,
    unique: true
  }
})
UserSchema.plugin(uniqueValidator)

module.exports = mongoose.model('Users', UserSchema)
  • 3
    The plugin is working fine but is there any other way which can resolve the issue without usage of plugin? – Lovika Nov 02 '17 at 00:14