reharis
reharis

Reputation: 412

'ObjectId' only refers to a type, but is being used as a value here.ts(2693)

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?

Upvotes: 4

Views: 5072

Answers (2)

Wheelwright
Wheelwright

Reputation: 75

I had the same problem so I just put this export at the top of a file I export type checking functions from.

import mongoose from "mongoose";

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

Upvotes: 0

reharis
reharis

Reputation: 412

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.

Upvotes: 8

Related Questions