I have searched but couldn't find a proper answer. I am new to stackoverflow and typescript. I am getting an error while creating a Mongoose Schema, my code looks like this:
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
},
-------
})
But it gives error that 'ObjectId' only refers to a type, but is being used as a value here.ts(2693)
tsconfig.json has the following content:
{
"compilerOptions": {
"incremental": true,
"target": "ES6",
"module": "commonjs",
"rootDir": "./src" ,
"baseUrl": "./src",
"outDir": "./build",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"include": ["src/**/*"]
}
I have also used mongoose.Types.ObjectId instead of ObjectId, but then get the following error:
Type 'typeof ObjectId' is missing the following properties from type 'typeof SchemaType': cast, checkRequired, set, getts(2322)
mongoose => 6.0.5
typescript => 4.4.3
what am I doing wrong?
Tried Using mongoose.Schema.Types.ObjectId instead of mongoose.ObjectId. and it worked.
my not-so-clear understanding of why it gave an error:
mongoose.ObjectId is an alias for type ObjectId = mongoose.Schema.Types.ObjectId which can only be used as a type, not as a "value" for type property in mongoose schema.
mongoose.Schema.Types.ObjectId refers to the actual class, hence can be used both as a type and value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With