Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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},
...});
like image 638
Yoni Mayer Avatar asked Jul 13 '17 05:07

Yoni Mayer


1 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);
like image 117
Ahmad Ahandani Avatar answered Nov 04 '22 03:11

Ahmad Ahandani