在 Mongoose 中将属性定义为 ObjectId 时出现 typescript 错误

标签 typescript mongoose mongoose-schema

我正在用 Mongoose 编写接口(interface)和模式,但遇到了一些 typescript 错误:

import { Schema, Types } from 'mongoose';

interface Foo {
  _id: Types.ObjectId,
  bar: Types.ObjectId,
}

const FooSchema = new Schema<Foo>({
  _id: { type: Types.ObjectId },
  bar: { type: Types.ObjectId },
});

属性_idbar在此代码中都有 typescript 错误:

Type '{ type: typeof Types.ObjectId; }' is not assignable to type 'SchemaDefinitionProperty | undefined'.
  Types of property 'type' are incompatible.
    Type 'typeof ObjectId' is not assignable to type 'typeof Mixed | ObjectIdSchemaDefinition | undefined'.
      Type 'typeof ObjectId' is missing the following properties from type 'typeof Mixed': schemaName, cast, checkRequired, set, get

Mongoose 版本是6.5.4(这是目前可用的最新版本)

我不知道为什么。这不是我第一次编写 mongoose schema,但没有遇到任何这样的问题。

我已经确认我可以从干净的新项目中重现此错误。 (表示没有其他背景原因)

最佳答案

在这里,尝试更改架构类型定义,如下所示:

const FooSchema = new Schema<Foo>({
  _id: { type: mongoose.Schema.Types.ObjectId },
  bar: { type: mongoose.Schema.Types.ObjectId },
});

说明:

根据 Mongoose 文档,SchemaType 与常规类型不同。换句话说,mongoose.ObjectId !== mongoose.Types.ObjectId。即 SchemaType mongoose.Schema.Types.ObjectId 是 Mongoose 使用的特殊定义。常规类型定义Types.ObjectId可用于创建接口(interface),但创建模式时必须使用SchemaType。是的,这有点令人困惑。就像 SchemaType 必须在架构中使用 String 而不是在接口(interface)中使用 string 一样,即使两者在技术上都是类型定义。希望这有帮助!

关于在 Mongoose 中将属性定义为 ObjectId 时出现 typescript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73554309/

相关文章:

node.js - 仅在 mongodb 聚合中返回具有最新子文档的文档

node.js - 使用 PATCH 修改 Node/ Mongoose 的多个条目?

javascript - cucumber JS : Custom parameter types not matching

javascript - 尝试使用 React + TypeScript 项目修复 tslint 错误

node.js - 类型 'virtual' 上不存在属性 'typeof Schema'

node.js - 如何在 Mongoose 中获取模型的 _id (Typescript)

node.js - Mongoose 中嵌套文档的不同类型是什么?

node.js - Mongoose 共享多个数据库的模型架构

javascript - 在 for 循环中使用 Model.create() 和 save()

typescript - Angular2 从集中数据中检测父级的变量变化