Home > Blockchain >  getting err in file sharing system using nodejs,express mongoose
getting err in file sharing system using nodejs,express mongoose

Time:10-02

This is my nodejs code

const mongoose = require('mongoose');

function connectDB() {
  //Database connection
  mongoose.connect(process.env.MONGO_CONNECTION_URL, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true,
    useFindAndModify: true
  });

  const connection = mongoose.connection;


  connection.once('open', () => {
    console.log('Database connected.');
  }).catch(err => {
    console.log('Connection failed.');
  })
}

module.exports = connectDB;

Showing this err while I am trying to connect with server

}).catch(err => {
            ^

TypeError: connection.once(...).catch is not a function

CodePudding user response:

Does it return a promise?

db.once('open', function(err, resp){
  console.log(resp);
});

Or


mongoose.connection
  .once('open', function () {
    console.log('MongoDB running');
  })
  .on('error', function (err) {
    console.log(err);
  });

CodePudding user response:

That's mean the once function does not return a promise object in the first place.

You can use catch with mongoose.connect to handle errors if there is any, check the example below:

function connectDB() {
    //Database connection
    mongoose.connect(
        process.env.MONGO_CONNECTION_URL,
        {
            useNewUrlParser: true,
            useCreateIndex: true,
            useUnifiedTopology: true,
            useFindAndModify: true
        }
    ).catch(err => console.log(err.reason));;

    const connection = mongoose.connection;

    connection.once('open', () => {
        console.log('Database connected.');
    })

}

  • Related