database - sasjakoning/blok-tech-2022 GitHub Wiki

To save elements online a database is needed. The Tech project of CMD which this feature is a part of highly suggested me to work with MongoDb due to its option to start a free database which is ideal for student projects.
MongoDB
Working with data doesn’t need to be hard
MongoDb is a noSQL database which uses JSON documents. It's data models are flexible and queries are faster than SQL databases.

Mongoose
Along with MongoDB I use Mongoose. Mongoose is a object modeling package for MongoDB which makes creating documents a lot easier. Mongoose also works very well with Express.
Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.

Connecting
To connect the MongoDB database to the project, I created a connect.js file.
In this file I write the following code:
require("dotenv").config();
const mongoose = require("mongoose");
const url = process.env.ATLAS_URI;
const connectDb = async () => {
try {
await mongoose.connect(url, {useNewUrlParser: true, useUnifiedTopology: true})
console.log("db connection succesful")
} catch (err) {
console.log(`failed to connect: ${err}`)
throw err
}
}
module.exports = {
connectDb
}
I first require a new file called .env which holds the connection url. a "dotenv" file is a zero-dependency module that loads environment variables into process. Using such a file is more secure than placing your credentials in your connect.js.
After writing the needed code I export the file by using module.exports and require it in my main back-end file.
Now I can communicate with the database through my code.