Anatoly
Anatoly

Reputation: 5243

TS2749: 'Schema' refers to a value, but is being used as a type here when defining Mongoose model with TypeScript

I am trying to find out what's wrong with my Mongoose model defined in the TypeScript project. Following this tutorial Strongly typed models with Mongoose and TypeScript I defined this model:

import mongoose from 'mongoose';
const { Schema, Document } = mongoose;

export interface IDoctor extends Document {
    firstName: string;
    lastName: string;
}

const DoctorSchema: Schema = new Schema({
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    }
});

export default mongoose.model<IDoctor>('Doctor', DoctorSchema);

But TypeScript complains that Schema and Document refer to a value, but is being used as a type here

I use "mongoose": "^5.9.24" and "@types/mongoose": "^5.7.32"

my tsconfig.json:

{
  "compilerOptions": {
    "extendedDiagnostics": false,
    "traceResolution": false,

    "noUnusedParameters": false,
    "noUnusedLocals": false,
    "allowUnusedLabels": false,

    "target": "es2017",
    "module": "esnext",
    "lib": [
      "es2019"
    ],
    "pretty": true,
    "sourceMap": true,
    "outDir": "dist",
    "importHelpers": true,
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "rootDir": "src",
    "noImplicitAny": false,
    "strictNullChecks": false,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "baseUrl": ".",
    "paths": {
      "*": [
        "node_modules/*",
        "src/types/*"
      ]
    },
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "resolveJsonModule": true
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "src/types/*"
  ]
}

Upvotes: 0

Views: 3468

Answers (1)

Code
Code

Reputation: 6251

mongoose does not appear to have a default export. So you should do:

import * as mongoose from 'mongoose';

Also, class types should be imported like:

import {Schema, Document} from 'mongoose';

Upvotes: 3

Related Questions