【问题标题】:Type 'ObjectId' does not satisfy the constraint 'MongooseDocument'类型“ObjectId”不满足约束“MongooseDocument”
【发布时间】:2019-09-19 17:59:26
【问题描述】:

我正在尝试使用 Typescript 将我的模型与猫鼬模式绑定。一切看起来都不错,除非我在 mongoose.Types.DocumentArray.

中使用 ObjectId
export interface TestModel extends mongoose.Document {
  name: string;
  sort: mongoose.Types.DocumentArray<mongoose.Schema.Types.ObjectId>;
}

const TestSchema = new mongoose.Schema({
  name: String,
  sort: [mongoose.Schema.Types.ObjectId]
});

export default mongoose.model<TestModel>('Test', TestSchema);

以下是我看到的错误

类型“ObjectId”不满足约束“MongooseDocument”。
类型“ObjectId”缺少类型中的以下属性 'MongooseDocument':$isDefault、$session、depopulate、equals 和 24 更多.ts(2344)

如果我使用

sort: [mongoose.Schema.Types.ObjectId];

而不是

sort: mongoose.Types.DocumentArray<mongoose.Schema.Types.ObjectId>;

在模式方面一切看起来都不错,但是在对模态结果进行操作时,我看到 .pull() 等方法出现 mongoose 类型错误(TS 没有将其作为 mongoose 数组类型。)

用这几个小时来抓挠我的头,任何帮助都将不胜感激。

【问题讨论】:

    标签: node.js typescript mongoose


    【解决方案1】:

    发现问题。我很愚蠢,这是一个愚蠢的错误,我在类型定义中使用了错误的类型。应该使用mongoose.Types.Array 而不是mongoose.Types.DocumentArray

    【讨论】:

      猜你喜欢
      • 2021-01-28
      • 1970-01-01
      • 2020-10-25
      • 2021-05-13
      • 2021-04-15
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 2022-11-10
      相关资源
      最近更新 更多