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},
...});
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With