Ace
Ace

Reputation: 132

mongoose.connect() is undefined

I'm trying to connect to my MongoDB using Mongoose and it gives me the following error.


const { mongoose } = require('mongoose');

const db = 'dburl.com/db'

mongoose.connect(db, { useNewUrlParser: true })
    .then(() => console.log('MongoDB Connected'))
    .catch((err) => console.log(err));

I get this Error

mongoose.connect(db, { useNewUrlParser: true })
         ^

TypeError: Cannot read property 'connect' of undefined

Upvotes: 1

Views: 1493

Answers (2)

NeNaD
NeNaD

Reputation: 20404

You should change 2 things:

  1. Change { mongoose } with mongoose
  2. Remove useNewUrlParser option. New version of Mongoose does not accept it as option and it will throw an error.
const mongoose = require('mongoose');

const db = 'dburl.com/db'

mongoose.connect(db)
    .then(() => console.log('MongoDB Connected'))
    .catch((err) => console.log(err));

Upvotes: 1

Ayush Kumar
Ayush Kumar

Reputation: 31

No need to destructure the mongoose in 1st line. Replace your 1st line of code with the below code. It should be work.

const mongoose = require('mongoose');

Upvotes: 3

Related Questions