mongoose: unique field isn't working

Viewed 2901

I'm trying to find out how to enforce unique on a field which isn't an index.

I've seen similar question in here, but the answer of using dropDups: true is mentioned to be depcrated.

what is the correct way of enforcing unique on a field?

const users = new Schema({
email: { type: String, required: true , unique: true},
...});
2 Answers

Use this mongoose-unique-validator

var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
 
// Define your schema as normal.
var userSchema = mongoose.Schema({
    username: { type: String, required: true, unique: true },
    email: { type: String, index: true, unique: true, required: true },
    password: { type: String, required: true }
});
 
// Apply the uniqueValidator plugin to userSchema.
userSchema.plugin(uniqueValidator);

Related