【问题标题】:'ObjectId' only refers to a type, but is being used as a value here.ts(2693)'ObjectId' 仅指一种类型,但在此处用作值。ts(2693)
【发布时间】:2021-11-12 00:54:37
【问题描述】:

我已经搜索但找不到正确的答案。我是stackoverflow和打字稿的新手。创建 Mongoose Schema 时出现错误,我的代码如下所示:

import  { Schema, ObjectId } from 'mongoose'

interface IArticle {
    title: string
    userId: ObjectId
    thumb: string
    slug: string
    children: object[]
    claps: number
}

const articleSchema = new Schema<IArticle>({
    -------
    userId: {
        type: ObjectId, // ERROR HERE!!!
        required: true
    },
    -------
})

但它给出了'ObjectId' only refers to a type, but is being used as a value here.ts(2693)的错误

tsconfig.json 有以下内容:

{
    "compilerOptions": {

        "incremental": true,

        "target": "ES6",
        "module": "commonjs",
        "rootDir": "./src" ,                       
        "baseUrl": "./src",
        "outDir": "./build",
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,

        "strict": true,
        "skipLibCheck": true
    },
    "include": ["src/**/*"]
}

我也使用了mongoose.Types.ObjectId而不是ObjectId,但随后出现以下错误:

Type 'typeof ObjectId' is missing the following properties from type 'typeof SchemaType': cast, checkRequired, set, getts(2322)

猫鼬 => 6.0.5
打字稿 => 4.4.3

我做错了什么?

【问题讨论】:

  • 不知道为什么你会收到这个错误,因为它对我来说很好用。你的Typescriptmongoose 是什么版本?您可以尝试使用mongoose.Types.ObjectId 而不是mongoose.ObjectId
  • @Kapobajza 我已经更新了问题,也尝试使用来自bsonmongodbObjectId,但得到类似的错误
  • @Kapobajza 解决了,谢谢。添加了答案。

标签: node.js typescript mongoose


【解决方案1】:

尝试使用mongoose.Schema.Types.ObjectId 而不是mongoose.ObjectId。并且成功了。

我的不太清楚理解为什么它会出错:

mongoose.ObjectIdtype ObjectId = mongoose.Schema.Types.ObjectId 的别名,它只能用作类型,不能用作猫鼬模式中类型属性的“值”。

mongoose.Schema.Types.ObjectId 指的是实际的类,因此可以用作类型和值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-07
    • 2020-04-28
    • 2021-08-23
    • 2020-12-05
    • 2018-03-31
    • 1970-01-01
    • 2023-04-03
    • 2023-04-05
    相关资源
    最近更新 更多