i think this is mainly a design-pattern challange. At the start of my Program i want to connect to my MongoDB Database and I'll get the connection object back.
//app.js
const start = async () => {
try {
const db = await mongoose.connect(process.env.MONGO_URI);
const port = process.env.PORT;
app.listen(port, console.log(`Server is listening on port ${port}...`));
} catch (error) {
console.error(error);
}
};
start();
registerCustomer
is a function that gets executed if a specific post request is send.
Inside registerCustomer
I want to use the db
object that gets runtime defined in the app.js
file. I want to write something like in the following code example but this will of course not work, because I have no access to the db
object.
const registerCustomer = async (req, res) => {
const session = await db.startSession(); //this will fail because I have no reference to the db object.
try {
session.startTransaction();
await Customer.create([{ firstName: "john" }], { session: session });
await Customer.create([{ firstName: "Doe" }], { session: session });
await session.commitTransaction();
} catch (error) {
await session.abortTransaction();
}
finally {
session.endSession();
}
How can I solve this problem the most elegant way? How can I access the db
object from other functions?
Thank you for reading.
app.js
|__database
|__conn.js
This is your MongoDB connection file fileName: conn.js
const mongoose = require("mongoose");
const DB = process.env.DATABASE;
mongoose
.connect(DB, {
useNewUrlParser: true,
})
.then((result) => {
console.log("Connection Successful on 'mongoosecrud' Cluster");
})
.catch((err) => {
console.log("Connection NOT Successful" + err);
});
Now simply you can require this connection file in your root server.js
or app.js
file
require("./database/conn.js")