Search code examples
node.jsmongodbmongoosemongoose-schema

How to create multiple index in mongoose schema


I'm trying to add multiple compound unique index in mongoose schema, but only the first schema.index() is working independent if I change the order.

import * as mongoose from 'mongoose';
const Schema = mongoose.Schema;

const PrivilegeSchema = new mongoose.Schema({
 
 application: {
    type: Schema.Types.ObjectId,
    required: true,
    ref: 'Application',
    autopopulate: true
  },
  section: {
    type: String,
    required: false
  },
  title: {
    type: String,
    required: false
  },
  permission: {
    type: String,
    required: true
  },
  active: {
    type: Boolean,
    required: true
  }
});

PrivilegeSchema.index( { permission: 1, application: 1 }, { unique: true, partialFilterExpression: {active: true} } );

PrivilegeSchema.index({ section: 1, title: 1, application: 1 }, { unique: true, partialFilterExpression: {active: true} });

export { PrivilegeSchema };

How can I set both schema index


Solution

  • I found the issue, the existing data in the collection is restricting the index to be created. Hence the following validation is throwing.

    enter image description here

    I removed whole data from the collection and now both the index got created.