【问题标题】:Nest.js - Create index in mongoose schemaNest.js - 在猫鼬模式中创建索引
【发布时间】:2021-04-01 21:56:30
【问题描述】:

如何使用 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 });

两者都没有按预期工作。

这样做的方法是什么?

谢谢

【问题讨论】:

  • 两种解决方案都应该有效,Document 是从猫鼬导入的吗?
  • 是的,文档是从 'mongoose' 导入的。运行该服务时,我收到此警告:DeprecationWarning: collection.ensureIndex is deprecated。改用 createIndexes,所以我猜,我的索引出了点问题,但这个集合中唯一的索引是“_id”
  • 如果已经在 mongodb 中设置了字段,您是否需要告诉架构一个字段是索引?

标签: node.js mongoose nestjs


【解决方案1】:

使用以下选项创建索引

    @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
}

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

【讨论】:

    【解决方案2】:

    如果有人来这里寻找如何为地理位置/2dsphere 添加索引,就像我一样,您可以在 NestJs 中使用以下内容。

    @Prop({ index: "2dsphere" })
    

    另外,当你设置猫鼬模块时,添加useCreateIndex: true

    MongooseModule.forRootAsync({
     useFactory: async (config: ConfigService) => ({
       uri: config.get('mongo_url'),
       useNewUrlParser: true,
       useCreateIndex: true,
     }),
     inject: [ConfigService],
    })
    

    【讨论】:

      【解决方案3】:

      这对我有用

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

      同样可以扩展为复合索引 - 例如:

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

      【讨论】:

        猜你喜欢
        • 2021-08-17
        • 2020-10-03
        • 2012-04-22
        • 2012-09-29
        • 2018-08-19
        • 2014-12-04
        • 2021-10-13
        • 2015-03-25
        相关资源
        最近更新 更多