Home > Enterprise >  How to connect mongoose to mongodb locally
How to connect mongoose to mongodb locally

Time:12-02

I just started learning to use node JS and I'm having difficulty connecting mongoose to mongodb using community version of mongdb locally.

const app = express();
app.use(bodyParser.json({extended: true}))
app.use(bodyParser.urlencoded({extended: true}))
app.use(cors());

app.get('/', (req, res)=>{
    react
})
 


const connectDB = 'mongodb://127.0.0.1/mydb';
mongoose.connect(connectDB, {useNewUrlParser: true, useUnifiedTopology:true})  //set up default mongoose connection


    let db = mongoose.connection; //Get the connection

    db.on('err', console.error.bind(console, 'MongoDB connection error:')); //Bind connection to error event

Whenever I run the server I do not see any sign that the database has connected and I do not have any error, the connection does not take place.Here is what I see on the console when I run the server

C:\projects\mongodb\backend>nodemon Server.js

> backend@1.0.0 start
> nodemon Server.js  

[nodemon] 2.0.15
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json  
[nodemon] starting `node Server.js`

The process of starting the server never runs to completion.

CodePudding user response:

You can use following code,

const mongoose = require('mongoose'); 

mongoose.connect(db_url,{ useNewUrlParser: true }, function (err) { 
if (err) throw err; console.log('Successfully connected'); });
  • Related