Skip to content

Instantly share code, notes, and snippets.

@peZhmanParsaee
Created May 30, 2020 14:14
Show Gist options
  • Save peZhmanParsaee/e1c1b1c7eae5354d4a06b790c8723e94 to your computer and use it in GitHub Desktop.
Save peZhmanParsaee/e1c1b1c7eae5354d4a06b790c8723e94 to your computer and use it in GitHub Desktop.
A correct way in connecting and disconnecting to MongoDb in Node.js
const url = require("url");
const parsedUrl = url.parse(
process.env.CONNECTION_STRING || "mongodb://localhost:27017/reactor"
);
module.exports = {
db: {
host: parsedUrl.hostname,
port: parseInt(parsedUrl.port, 10),
name: parsedUrl.pathname.substr(1),
user: parsedUrl.auth ? parsedUrl.auth.split(":")[0] : null,
password: parsedUrl.auth ? parsedUrl.auth.split(":")[1] : null,
url: parsedUrl.href
}
};
const express = require("express");
const http = require("http");
const dbConnection = require("./mongoDbConnectionSingleton"); // it is here: https://gist.github.com/peZhmanParsaee/e7e25a17dd36a70bf6289187cab2c994
const app = express();
app.get("/", async (req, res) => {
try {
const db = dbConnection.getDb();
const result = await db.collection("CUSTOMERS").find({}).toArray();
res.send(result);
} catch (e) {
console.error(e);
}
});
dbConnection
.getInstance()
.then((connection) => {
const server = http.createServer(app);
server.listen(4445, () => {
const addr = server.address();
console.log(
`API is up and running at ${addr.address} and port number ${addr.port}`
);
});
})
.catch((e) => {
console.error(e);
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment