Yoni Mayer
Yoni Mayer

Reputation: 1238

mongoose: unique field isn't working

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},
...});

Upvotes: 6

Views: 2991

Answers (2)

Ahmad Ahandani
Ahmad Ahandani

Reputation: 111

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);

Upvotes: 7

JosephM
JosephM

Reputation: 2935

If you do it like this, It will not work for unique key validation.

var userSchema = new Schema({
    name : String,
    username : {
        type : String,
        required : true,
        index : {
            unique : true,
            dropDups : true
        }
    });

So you doing it in correct and best way right now, just do it like this

Drop the collection from database using following command

> db.<collection name>.drop()

Then restart server and check by doing in this way.

var userSchema = new Schema({
    name : String,
    username : {
        type : String,
        required : true,
        unique : true
    });

Upvotes: 0

Related Questions