Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 381
Nick Hodges Avatar asked Sep 15 '19 13:09

Nick Hodges


People also ask

How do you connect to the database with mongoose?

Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB. mongoose. connect('mongodb://localhost:27017/myapp'); const MyModel = mongoose. model('Test', new Schema({ name: String })); // Works MyModel.

Which mongoose method is used to connect to the database?

You can require() and connect to a locally hosted database with mongoose. connect() , as shown below. You can get the default Connection object with mongoose.

How does mongoose Connect work?

Mongoose will try to connect with the MongoClient internally and return the instance of mongoose. this is the internal process of "conn. openUri" function and mongoose will execute the function. you can also connect the mongoClient directly without using mongoose.

What is the difference between mongoose connect and mongoose createConnection?

connect() is use, whereas if there is multiple instance of connection mongoose. createConnection() is used. Hope someone can clarify more about this.


1 Answers

Replace:

import * as mongoose from "mongoose";

With:

import mongoose from "mongoose";
like image 195
Vijay Shaaruck Avatar answered Sep 18 '22 13:09

Vijay Shaaruck