From the code in the previous section, you can see that we should always import MongoClient, providing the MongoDB server URL, database name, and so on whenever performing a MongoDB CRUD task. This can be tedious and counter-productive. Let's abstract the preceding MongoDB connection code into a class in the following steps:
- Abstract the database connection details into a file:
// server/config/mongodb.js
const database = {
host: 'localhost',
port: 27017,
dbname: 'nuxt-app'
}
export default {
host: database.host,
port: database.port,
dbname: database.dbname,
url: 'mongodb://' + database.host + ':' + database.port
}
- Create a class function to construct the database connection so that we don't have to repeat this process whenever we perform the CRUD operations. We also construct an objectId property in our class function for storing the ObjectId method that we will need in order to parse...