Skip to content

Latest commit

 

History

History
42 lines (33 loc) · 929 Bytes

03_DataBaseConnection.md

File metadata and controls

42 lines (33 loc) · 929 Bytes

MongoDB DataBase Connection

import mongoose from "mongoose";

const Database = async () => {
  const url = "mongodb://localhost/messages";
  await mongoose.connect(url, {
    useNewUrlParser: true,
  });
  const connect = mongoose.connection;
  connect.on("open", () => {
    console.log("Database Connect Successfully");
  });
};

export default Database;
  1. It connects to the MongoDB cluster using the Mongoose library and the URI:
mongoose.connect(uri, {
  useNewUrlParser: true,
  useCreateIndex: true,
  useUnifiedTopology: true,
});
  1. It creates a connection variable to the MongoDB cluster:
const connection = mongoose.connection;

2- It listens for a 'open' event on the connection, which will be emitted when the connection to the MongoDB cluster is established:

connection.once("open", () => {
  console.log("MongoDB database connection established successfully");
});