Mongoose: how to define a combination of fields to be unique?

Mongoose

Mongoose Problem Overview


If I had a schema like this:

var person = new Schema({
  firstName:  String,
  lastName: String,
});

I'd like to ensure that there is only one document with the same firstName and lastName.

How can I accomplish this?

Mongoose Solutions


Solution 1 - Mongoose

You can define a unique compound index using an index call on your schema:

person.index({ firstName: 1, lastName: 1}, { unique: true });

Solution 2 - Mongoose

Fun little thing I only recently discovered through experimentation with Mongoose. I have the following schema for example:

const ShapesSchema = new mongoose.Schema({
  name: { type: String, required: true },
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
})

ShapesSchema.index({ name: 1, user: 1 }, { unique: true })

mongoose.model('Shapes', ShapesSchema)

The idea was to create a compound index that was unique on name and user together. This way a user could create as many shapes as they wanted as long as each of their shapes had a distinct name. And the inverse was supposed to be true as well - shapes could have the same name as long as they had different users. It didn't work out like that for me.

What I noticed was that aside from the index on _id, three other index entries were created. One each for name, user, and name_user all set to be unique. I made a modification to the schema and included unique: false to each of the fields I was using for the compound index and suddenly it all worked as expected. What I ended up with was:

const ShapesSchema = new mongoose.Schema({
  name: { type: String, required: true, unique: false },
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', unique: false }
})

ShapesSchema.index({ name: 1, user: 1 }, { unique: true })

mongoose.model('Shapes', ShapesSchema)

Looking at the indexes that were created as a result I still see the three indexes - name, user, and name_user. But the difference is that the first two are not set to be unique where the last one, the compound, is. Now my use case of multiple distinct shapes per user, or identically named shapes with different users works like a champ.

Solution 3 - Mongoose

defining your schema like this


var person = new Schema({
firstName:  String,
lastName: String,
index: true,
unique: true, 
  
});

or


person.index({ firstName: 1, lastName: 1}, { unique: true });

Solution 4 - Mongoose

const personSchema = new Schema({ firstName:  String, lastName: String });
const person = mongoose.model('recipients', personSchema);
person.createIndexes();

You might need to get rid of all duplicates in the collection or do it the faster and easy way : > Edit your Code, Drop the Collection and then restart Mongo.

Solution 5 - Mongoose

I haven't tried this, but using a unique index should do the trick.

db.person.ensureIndex( { "firstname": 1, "lastname": 1 }, { unique: true } )

Solution 6 - Mongoose

You can define Your Schema like this.

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const bcrypt = require("bcryptjs");

    const userSchema = new Schema({
      firstName: {
        trim: true,
        type: String,
        required: [true, "firstName is required!"],
        validate(value) {
          if (value.length < 2) {
            throw new Error("firstName is invalid!");
          }
        }
      },
      lastName: {
        trim: true,
        type: String,
        required: [true, "lastName is required!"],
        validate(value) {
          if (value.length < 2) {
            throw new Error("lastName is invalid!");
          }
        }
      },
      username: {
        unique: [true, "Username already available"],
        type: String,
        required: [true, "Username is required"],
        validate(value) {
          if (value.length < 10) {
            throw new Error("Username is invalid!");
          }
        }
      },
      mobile: {
        unique: [true, "Mobile Number alraedy available"],
        type: String,
        required: [true, "Mobile Number is required"],
        validate(value) {
          if (value.length !== 10) {
            throw new Error("Mobile Number is invalid!");
          }
        }
      },
      password: {
        type: String,
        required: [true, "Password is required"],
        validate(value) {
          if (value.length < 8) {
            throw new Error("Password is invalid!");
          }
        }
      },
      gender: {
        type: String
      },
      dob: {
        type: Date,
        default: Date.now()
      },
      address: {
        street: {
          type: String
        },
        city: {
          trim: true,
          type: String
        },
        pin: {
          trim: true,
          type: Number,
          validate(value) {
            if (!(value >= 100000 && value <= 999999)) {
              throw new Error("Pin is invalid!");
            }
          }
        }
      }
      date: { type: Date, default: Date.now }
    });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmartinpaulucciView Question on Stackoverflow
Solution 1 - MongooseJohnnyHKView Answer on Stackoverflow
Solution 2 - MongooseldapmonkeyView Answer on Stackoverflow
Solution 3 - MongooseDeeksha SharmaView Answer on Stackoverflow
Solution 4 - MongooseAkintundeView Answer on Stackoverflow
Solution 5 - Mongooseuser1738206View Answer on Stackoverflow
Solution 6 - MongooseAnkit Kumar RajpootView Answer on Stackoverflow