Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

365
Views
How to close mongodb properly?

I am new to backend and mongodb. I don't know how to close mongodb . Please help with that. Thanks in advance.

index.js

const server = require("./server");

const port = process.env.PORT || 5100;
process.on("exit", function () {
  console.log("db disconnected");
  mongoose.disconnect();
});
server
  .create()
  .then((app) => {
    app.listen(port, () => {
      console.log(`Server has started on port ${port}!`);
    });
  })
  .catch((err) => console.log(err));

server.js

const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv").config();

const create = async () => {
  const app = express();
  //DB connection
  mongoose
    .connect(process.env.DB_STRING, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })
    .then(() => console.log("MongoDB Connected"))
    .catch((err) => console.log(err));

  //Allowing cors
  app.use(cors());
  //Body parser
  app.use(express.json());

  //Middleware configuration

  //   app.use("/api/test", require("./routes/testingroute"));
  app.get("/", (req, res) => res.send("Hello World!"));

  app.use("/api/user", require("./routes/userRoute"));

  return app;
};

module.exports = {
  create,
};

this is what i have tried till now.i can able to access my db but i am not sure about the closing db properly.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

mongoose.disconnect();

Should close the DB.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!