【发布时间】: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
我做错了什么?
【问题讨论】:
-
不知道为什么你会收到这个错误,因为它对我来说很好用。你的
Typescript和mongoose是什么版本?您可以尝试使用mongoose.Types.ObjectId而不是mongoose.ObjectId -
@Kapobajza 我已经更新了问题,也尝试使用来自
bson和mongodb的ObjectId,但得到类似的错误 -
@Kapobajza 解决了,谢谢。添加了答案。
标签: node.js typescript mongoose