我已经搜索过,但没有找到合适的答案。我是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。
我做错了什么?
Typescript
和mongoose
版本是多少?你可以尝试使用mongoose.Types.ObjectId
代替mongoose.ObjectId
。 - Kapobajzabson
和mongodb
中的ObjectId
,但是出现了类似的错误。 - userharis