我搜索了一下,但沒有找到合適的答案。我是 stackoverflow 和 typescript 的新手。我在創建Mongoose Schema時遇到了一個錯誤,我的代碼是這樣的:
import { Schema, ObjectId } from 'mongoose'
介面 IArticle {
title: string
userId: ObjectId[/span].
thumb: string
slug: string
children: object[] 。
claps: number
}
const articleSchema = new Schema<Article> ({
-------
userId: {
type: ObjectId, // ERROR HERE!!!.
required: true。
},
-------
})
但它給出的錯誤是'ObjectId'只指一個型別,但在這里被用作一個值。ts(2693)
tsconfig.json的內容如下:
{
"compilerOptions"/span>: {
"incremental": true,
"目標": "ES6"。
"模塊"。"commonjs",
"rootDir": "./src" ,
"baseUrl": "./src",
"outDir": "./build",
"esModuleInterop": true。
"forceConsistentCasingInFileNames": true,
"strict"。true,
"skipLibCheck": true。
},
"include": ["src/**/*"]
}
我也曾用mongoose.Types.ObjectId代替ObjectId,但隨后得到以下錯誤:
型別'typeof ObjectId'在型別'typeof SchemaType'中缺少以下屬性:cast, checkRequired, set, getts(2322)
mongoose => 6.0.5
typescript => 4.4.3
我做錯了什么?
uj5u.com熱心網友回復:
嘗試使用mongoose.Schema.Types.ObjectId而不是mongoose.ObjectId.并且成功了。
我的不是很清楚的理解,為什么會出現錯誤:
mongoose.ObjectId是type ObjectId = mongoose.Schema.Types.ObjectId的別名,它只能作為一個型別使用,不能作為mongoose模式中型別屬性的 "值"。
mongoose.Schema.Types.ObjectId指的是實際的類,因此可以同時作為型別和值使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/331069.html
標籤:
