Home > front end >  how to use async and await to connect to mongoDB database?
how to use async and await to connect to mongoDB database?

Time:02-12

I am new to JavaScript and currently learning mongoDB with node. The code Bellow is in callback functions but i want to connect to mongoDB database using async and await with try and catch .

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost/selfdb");

mongoose.connection
  .once("open", () => {
    console.log("connection has been made!");
  })
  .on("error", (error) => {
    console.log("connection error:", error);
  });

I tried doing this way:

const mongoose = require("mongoose");

async function main() {
  const uri = "mongodb://localhost/selfdb";

  const client = new mongoose(uri);

  try {
    await client.connect();
    console.log("connection has been made!");
  } catch (e) {
    client.error(e);
  } finally {
    await client.close();
  }
}

main().catch(console.error);

but i got following error:

TypeError: mongoose is not a constructor

how could i do it the right way? am i doing any silly mistake?

CodePudding user response:

I believe the better way to connect is like this

const mongoose = require('mongoose')

const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI)
    console.log(`MongoDB Connected: ${conn.connection.host}`)
  } 
  catch (error) {
    console.log(error)
    process.exit(1)
  }
}

module.exports = connectDB

Mongo URI is in .env file, but you can replace it with your connection string (but more secure in .env file)

Then in server.js or index.js (entry file)

const connectDB = require('path_to_file')

connectDB()
  • Related