Search code examples
node.jsmongodbtypescriptexpressmongoose

Why am I getting "mongoose.connect is not a function" when trying to connect with mongoose?


I am new to Node.js and am trying to build a node/express/mongoose server app with TypeScript.

Here is my app.ts file:

// lib/app.ts
import express from 'express';
import * as bodyParser from 'body-parser';
import { Routes } from './routes/crmRoutes';
import * as mongoose from "mongoose";

class App {
  public app: express.Application;
  public routePrv: Routes = new Routes();
  public mongoUrl: string = 'mongodb://localhost/TodosDB';

  constructor() {
    this.app = express();
    this.config();
    this.routePrv.routes(this.app);
    this.mongoSetup();
  }

  private mongoSetup(): void {
    mongoose.connect(this.mongoUrl, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
  }

  private config(): void {
    // support application/json type post data
    this.app.use(bodyParser.json());
    //support application/x-www-form-urlencoded post data
    this.app.use(bodyParser.urlencoded({ extended: false }));
  }
}

export default new App().app;

However, when I try to compile my application, I get:

TypeError: mongoose.connect is not a function

I've used up all my Google skill -- no luck.

Can anyone tell me what I'm doing wrong?


Solution

  • Replace:

    import * as mongoose from "mongoose";
    

    With:

    import mongoose from "mongoose";