Home > Net >  Node js can't connect to my database using mongoose
Node js can't connect to my database using mongoose

Time:04-17

I am trying to use use hyper terminal to connect to my mongodb database (created with mongoose) and when I use node app.js to try to connect to the database using hyper terminal, my terminal just freezes and return no response until I press ctrl c to exit and return to the previous line.

My mongoose code looks like the following:

const mongoose = require('mongoose');

mongoose.connect('mongodb://127.0.0.1:27017/fruitsDB');

Please note. I have already connected to the mongodb server by using mongodin the terminal and I have also cd to the directory of my folder where the app.js is located on my pc before running the node app.js on the terminal

screenshort of my terminal hyerterminal code screen

Please I need your help. Thank you

CodePudding user response:

I believe that your terminal is NOT frozen, it is just that there is no console output in your code. You are connecting to Mongoose and then doing nothing after that.

Here are some suggestions,

You can use a callback to check if the connection is connected,

mongoose.connect('mongodb://127.0.0.1:27017/fruitsDB').then(
  () => { 
     console.log("Connected to DB!");
 },
  err => { 
    console.log(err);
 }
);

Add a few event handlers to check if your connection is working,

mongoose.connection.on('open', function(){
  console.log("Connection to Mongo DB is open!");
});

If you want to check for errors during "connect", you can chain an error handler in catch block.

mongoose.connect('mongodb://localhost:27017/test').
  catch(error => console.log(error));

If you want to use Async/Await for the same error handling, then follow the below.

(async () => {
    try {
      await mongoose.connect('mongodb://localhost:27017/test');
      console.log("Successfully connected to Mongo DB");
    } catch (error) {
      console.log(error);
    }
})();

If you want to catch errors happening after the connection is connected to Mongo DB,

mongoose.connection.on('error', err => {
  console.log(error);
});
  • Related