首页 > 解决方案 > Nest.js - 在猫鼬模式中创建索引

问题描述

如何使用 Nest.js 在猫鼬模式中创建属性索引?

我尝试将索引添加为属性选项,但尚未创建索引:

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

我也试过这种方式:

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

两者都没有按预期工作。

这样做的方法是什么?

谢谢

标签: node.jsmongoosenestjs

解决方案


使用以下选项创建索引

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

useCreateIndex在定义架构时使用标志

或在创建连接对象时全局设置相同的标志

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

还添加了其他可能需要的注释标志。


推荐阅读