I’m building a simple MERN stack application and I want to build the backend REST API using the most current MongoDB connection methods. My app is currently functional. However, I want to be sure I am connecting to MongoDB properly, specifically in a Node Express app that has routes in separate files.
Here are the main files in my project backend:
-
server/
- db
- conn.js
- routes
- record.js
- server.js
- config.env
- db
As my starting place, I am using this (outdated) tutorials:
Both of these tutorials connect to MongoDB using an older callback method. (See links above or code snippets further below). I would like to use a more current method, as exampled here, but in both cases the code is contained in a single file:
-Node.js Connection Guide
-Connect to a MongoDB Database Using Node.js
This is the code that the older tutorials suggests to export the connection from the conn.js file:
module.exports = {
connectToServer: function (callback) {
client.connect(function (err, db) {
// Verify we got a good "db" object
if (db)
{
_db = db.db("employees");
console.log("Successfully connected to MongoDB.");
}
return callback(err);
});
},
getDb: function () {
return _db;
},
};
And this is how I have currently refactored it:
module.exports = {
async connectToServer() {
try {
dbConnection = client.db("employees");
console.log("Successfully connected to MongoDB.");
} catch (err) {
console.log(`Error connecting to MongoDB: ${err}`);
}
},
getDb: function () {
return dbConnection;
}
};
If you have any suggestions or pointers for me, I welcome them. Thanks in advance!