Skip to content Skip to sidebar Skip to footer

How To Index Multiple Unique Data Fields In A Single Document In Mongoose?

In my user document, I want to individually index email and username as unique fields, so that a duplicate is never entered. The problem is all of the documentation I have found f

Solution 1:

Mongoose doesn't have a built-in validation for unique fields. I recommend the package (with this you can use the unique validator on the email and username fields): mongoose-unique-validator. Extend your code with:

let uniqueValidator = require('mongoose-unique-validator');

email: {
  type: String,
  required: true,
  trim: true,
  unique: true,
  index: true
},
  username: {
  type: String,
  required: false,
  trim: true,
  unique: true,
  index: true
}

UserSchema.plugin(uniqueValidator, {message: 'is already taken.'});

Solution 2:

Add unique: true to each field's definition in the schema to create separate, unique indexes for those fields:

const UserSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    trim: true,
    unique: true
  },
    username: {
    type: String,
    required: false,
    trim: true,
    unique: true
  }
})

See the Indexes section on this page for the documentation.


Post a Comment for "How To Index Multiple Unique Data Fields In A Single Document In Mongoose?"