You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS中MongoDB索引自动删除及hint报错问题求助

NestJS(9+)+ MongoDB 6.0.5副本集:索引自动删除与hint报错问题

在NestJS 9+版本环境下使用MongoDB 6.0.5副本集时,出现以下异常:创建集合的普通或复合索引后,索引会自动被删除;调用MongoDB的hint()方法时抛出错误:

Collation: { locale: "simple" } planner returned error :: caused by :: hint provided does not correspond to an existing index

需要创建索引的字段定义

@Prop({ required: true, type: ProductSubset, default: null })
reviewedItem: ProductSubset;

@Prop({ required: false, min: 0, default: 0 })
rating: number;

尝试过的索引创建方式

  • 方式1:
MySchema.index({ 'reviewedItem._id': 1, rating: 1 }, { unique: true });
  • 方式2:
MySchema.index({ 'reviewedItem._id': 1 }, { unique: true });
  • 方式3:
MySchema.index({ 'rating': 1 }, { unique: true });
  • 方式4:
export const MySchema = SchemaFactory.createForClass(Class).index(
  { 'reviewedItem._id': 1, rating: 1 },
  { unique: true },
);

异常场景

  • 创建索引后,在MongoDB Compass的集合索引页面能看到该索引,但刷新3-4次后,索引大小增长至约4MB时突然被删除;
  • 若不刷新Compass,调用接口时索引会自动消失,触发上述hint报错。

MongoDB日志(翻译后)

第二条日志:

"attr": {
    "code": "BABEL_PARSE_ERROR",
    "reasonCode": "MissingSemicolon",
    "loc": {
      "line": 1,
      "column": 2,
      "index": 2
    },
    "pos": 2,
    "message": "缺少分号。(1:2)\n\n\u001b[0m\u001b[31m\u001b[1m>\u001b[22m\u001b[39m\u001b[90m 1 |\u001b[39m cd nano  \u001b[33m/\u001b[39m\u001b[36mvar\u001b[39m\u001b[33m/\u001b[39mlog\u001b[33m/\u001b[39mmongodb\u001b[33m/\u001b[39mmongod\u001b[33m.\u001b[39mlog\u001b[0m\n\u001b[0m \u001b[90m   |\u001b[39m   \u001b[31m\u001b[1m^\u001b[22m\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m 2 |\u001b[39m\u001b[0m",
    "name": "SyntaxError",
    "stack": "SyntaxError: 缺少分号。(1:2)\n\n\u001b[0m\u001b[31m\u001b[1m>\u001b[22m\u001b[39m\u001b[90m 1 |\u001b[39m cd nano  \u001b[33m/\u001b[39m\u001b[36mvar\u001b[39m\u001b[33m/\u001b[39mlog\u001b[33m/\u001b[39mmongodb\u001b[33m/\u001b[39mmongod\u001b[33m.\u001b[39mlog\u001b[0m\n\u001b[0m \u001b[90m   |\u001b[39m   \u001b[31m\u001b[1m^\u001b[22m\u001b[39m\u001b[0m\n\u001b[0m \u001b[90m 2 |\u001b[39m\u001b[0m\n"
  }

最后一条日志:

"msg": "刷新未写入的数据",
  "attr": {
    "flushError": null,
    "flushDuration": 0
  }

内容的提问来源于stack exchange,提问作者M Nouman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 12:43:17