首页 > 解决方案 > mongoose 设置架构索引在版本更新后抛出异常,属性“key”丢失但在“IndexSpecification”类型中是必需的

问题描述

我曾经使用以下语法设置架构索引:

mySchema.index({ name: 'text' });

name的架构的属性也是如此。

猫鼬更新后,我收到以下错误:

Argument of type '{ name: string; }' is not assignable to parameter of type 'IndexSpecification'.
  Property 'key' is missing in type '{ name: string; }' but required in type 'IndexSpecification'.ts(2345)

我应该在这里设置什么键?

猫鼬版本:

mongoose@^5.13.6

@types/mongoose@^5.11.97

谢谢!

标签: node.jsmongoose

解决方案


按照 mongodb 文档,

钥匙:

指定索引的字段。对于每个字段,指定一个键值对,其中键是要索引的字段的名称,值是索引方向或索引类型。如果指定方向,指定 1 表示升序或 -1 表示降序。

所以答案是:

mySchema.index({ key: { name: 1 }, name: 'nameIndex' });


推荐阅读