NodeJs express and mongodb basic setup

25 Views Asked by At

There is any way to make this Node.Js x MongoDB setup more simpler? In this example project i 'm using a Movies collection to test the routes and the CRUD methods.

This simple project is handling the movies in the database, you can add new movie to the database, you can delete, update or edit. Eevery time when the app start running the database get loaded with 3 movie for testing reasons. I made the project as compact as I could, but I think it could be shorter and easier to understand.

app.js

//npm init
//npm i express
//npm i mongodb
//npm i bootstrap
//npm i body-parser
//npm i pug

const express = require('express');
const bodyparser = require('body-parser');
const app = express();
const path = require('path');

const server = app.listen(5600, () => {
    console.log("Server initialized");
});

// Use body-parser middleware to parse incoming requests
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:true}));

//static routes
app.use('/bootstrap', express.static('./node_modules/bootstrap/dist'))
app.use('/views', express.static('./views'))


//Require movies routes
const movies = require('./routes/movies');
const { AsyncLocalStorage } = require('async_hooks');


app.set('view engine', 'pug');
app.set('views','./views');

const {MongoClient} = require("mongodb");
const mongo = require('./mongo');

app.use('/', movies);



//Upload Database for testing (Optional)
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

const dataBaseName = "MovieDirectory";

async function main() {

    await mongo.dropCollection(client,dataBaseName,"Movies");
    await mongo.insertMany(client, dataBaseName, "Movies",[
        {
            "title": "Star Wars: The Last Jedi",
            "director":"Rian Johnson",
            "releaseDate":  1983,
            "imdbRating": 5.6
        },
        {
            "title": "The Lord of the Rings: The Return of the King",
            "director":"Peter Jackson",
            "releaseDate":  2004,
            "imdbRating": 7.9
        },
        {
            "title": "Interstellar",
            "director":"Christopher Nolan",
            "releaseDate":  2014,
            "imdbRating": 8.6
        }
    ]);
}
main().catch(console.error).finally(() => client.close());

mongo.js

const { json } = require("body-parser");

// Function to get collection reference
async function getCollection(client, database, collection) {
const dbObj = await client.db(database);
return dbObj.collection(collection);
}

/*----------------- CRUD Methods -----------------*/

// Create
async function insertOne(client, database, collection, document) {
const col = await getCollection(client, database, collection);
return await col.insertOne(document);
}

// Read all Data
async function listAll(client, database, collection) {
const col = await getCollection(client, database, collection);
return await col.find({}).toArray();
}

// Update
async function updateOne(client, database, collection, filterField, filterValue, setField, setValue) {
const col = await getCollection(client, database, collection);
let filter = { \[filterField\]: filterValue };
let valSet = { $set: { \[setField\]: setValue } };
return await col.updateOne(filter, valSet);
}

// Delete
async function deleteOne(client, database, collection, field, value) {
const col = await getCollection(client, database, collection);
return await col.deleteOne({ \[field\]: value });
}

//Find
async function find(client, database, collection, field, value) {
const col = await getCollection(client, database, collection);
    const result = await col.find({ [field]: value }).toArray();
    return result[0]; 
}

/*----------------- Optional -----------------*/

async function insertMany(client, database, collection, documents) {
const col = await getCollection(client, database, collection);
return await col.insertMany(documents);
}

async function dropCollection(client, database, collection) {
const dbObj =  await(await getCollection(client, database, collection)).drop();
console.log(`${collection} collection was dropped successfully`);
}

module.exports ={
insertOne : insertOne,
insertMany : insertMany,
listAll: listAll,
updateOne : updateOne,
deleteOne: deleteOne,
find: find,
dropCollection: dropCollection
}

movies.js (contains the routes)

const express = require('express');
const router = express.Router();

// Import MongoClient from MongoDB library
const { MongoClient, ObjectId } = require("mongodb");

// Import the mongo.js file
const mongo = require('../mongo');

const { render } = require('pug');

// MongoDB connection URL
const url = 'mongodb://localhost:27017';

// Create a new MongoClient instance
const client = new MongoClient(url);

/\* Constants for database names \*/
const dataBaseName = "MovieDirectory";

/*----------------- CRUD Routes -----------------*/

//Read (Display all movie)
router.get('/', async (req, res) =\> {
const movies = await mongo.listAll(client, dataBaseName, "Movies");
res.render("index", { "movies": movies });
});

//Create
router.get('/create', async (req, res) =\> {
res.render("create", { "success": success, "movieFeedback": movieFeedback });
});

router.post('/store', async (req, res) =\> {
await mongo.insertOne(client, dataBaseName, "Movies", {
"title": req.body.title,
"director": req.body.director,
"releaseDate": parseInt(req.body.releaseDate),
"imdbRating": parseFloat(req.body.imdbRating)
});
res.redirect("/create");
});

//Update
router.post('/edit', async (req, res) =\> {
const item = await mongo.find(client, dataBaseName, "Movies", "\_id", new ObjectId(req.body.id))
res.render("edit", { "editItem": item })
});

router.post('/update', async (req, res) =\> {
await mongo.updateOne(client, dataBaseName, "Movies", "\_id", new ObjectId(req.body.id), "title", req.body.title);
await mongo.updateOne(client, dataBaseName, "Movies", "\_id", new ObjectId(req.body.id), "director", req.body.director);
await mongo.updateOne(client, dataBaseName, "Movies", "\_id", new ObjectId(req.body.id), "releaseDate", req.body.releaseDate);
await mongo.updateOne(client, dataBaseName, "Movies", "\_id", new ObjectId(req.body.id), "imdbRating", req.body.imdbRating);

    res.redirect("/");

});

//Delete
router.post('/delete', async (req, res) =\> {
await mongo.deleteOne(client, dataBaseName, "Movies", "\_id", new ObjectId(req.body.id));
res.redirect("/")
});
0

There are 0 best solutions below