Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nest.js - Create index in mongoose schema

How do I create an index of property in mongoose schema using Nest.js?

I tried to add index as a property option, But the index hasn't been created:

@Schema()
export class Schema extends Document {

  @Prop()
  _id: string;

  @Prop({required: true, index: true})
  type: string;

  @Prop()
  creationDate: string;

  @Prop()
  name: string;
}

export const MySchema = SchemaFactory.createForClass(Schema);

I tried this way too:

export const MySchema = SchemaFactory.createForClass(Schema).index({ type: 1 });

Both doesn't work as expected.

What is the way to do that?

Thanks

like image 258
user2436448 Avatar asked Dec 06 '22 08:12

user2436448


1 Answers

Use following option to create index

    @Schema({useCreateIndex: true})
    export class Schema extends Document {
    
      @Prop()
      _id: string;
    
      @Prop({required: true, index: true})
      type: string;
    
      @Prop()
      creationDate: string;
    
      @Prop()
      name: string;
    }

export const MySchema = SchemaFactory.createForClass(Schema);

use useCreateIndex flag either when defining the schema

or globally set the same flag when creating the connection object

 {
  uri: `....`,
  user: ,
  pass: ,
  //useNewUrlParser: true,
  useCreateIndex: true,
  //useUnifiedTopology: true,
  //useFindAndModify: false,
  retryAttempts: 3
}

Added other commented flags as well which could be required.

like image 200
AZ_ Avatar answered Dec 30 '22 10:12

AZ_