"ObjectId" 只是一个类型的名称,但在此处被用作一个值。ts(2693)

4

我已经搜索过,但没有找到合适的答案。我是stackoverflow和typescript的新手。在创建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'只是一个类型的引用,但在此处被用作值.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' 缺少类型 'typeof SchemaType' 的以下属性:cast、checkRequired、set、getts(2322)

mongoose版本为6.0.5,typescript版本为4.4.3。

我做错了什么?


不知道为什么你会遇到这个错误,因为它在我的电脑上运行得很好。你使用的 Typescriptmongoose 版本是多少?你可以尝试使用 mongoose.Types.ObjectId 代替 mongoose.ObjectId - Kapobajza
@Kapobajza 我已经更新了问题,还尝试使用bsonmongodb中的ObjectId,但是出现了类似的错误。 - userharis
@Kapobajza已经解决了,谢谢。我添加了一个答案。 - userharis
2个回答

8

尝试使用 mongoose.Schema.Types.ObjectId 替代 mongoose.ObjectId,它可以正常工作。

我对为什么会出现错误的理解不太清晰:

mongoose.ObjectIdtype ObjectId = mongoose.Schema.Types.ObjectId 的别名,只能用作类型,而不能将其作为 mongoose 模式中 type 属性的“值”。

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


0

我曾经遇到过同样的问题,所以我只是在一个文件的顶部放置了这个导出语句,从中导出类型检查函数。

import mongoose from "mongoose";

export type TObjectId = mongoose.ObjectId;
export const ObjectId = mongoose.Types.ObjectId;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接