MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

Setting unique compound index in schema definition

I would like to have a combination of 3 keys (type, parent and name) as unique compound index. I defined the schema as follows, but I can still create a unit that has the same type, parent and name. What am I missing?

  const unitSchema = new mongoose.Schema({
    name: {
      type: String,
      required: true,
    },
    type: {
      type: String,
      required: true,
    },
    parent: {
      type: String,
      required: true,
    },
    administrators: {
      type: Array,
      required: true,
    },
  });

  unitSchema.index({ type: 1, parent: 1, name: 1 }, { unique: true });

  const Unit = mongoose.model('Unit', unitSchema);

I am wondering of this may help

Thank you @Natac13! It worked!!

As the author of this article says, it’s pretty weird that we have to use mongoose-unique-validator to accomplish this.

There is also this option I remembered