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

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


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

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

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.


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.

Tags:

Mongoose