Share
Explore

Adding MONGO DB to your Full Stack Node Web App

Considering that the application as it has been designed so far stores data (on books) in program memory, we will lose our records everytime to program ends.

Next step is to build the MODEL with MONGO db.

I want you to design a Node.js JavaScript Program which will use MONGOOSE NODE API to build a MONGO DB server to store the book objects: persist to MONGO Documents and Collections the BOOK OBJECTS currently being stored in the let books = [] array.
Here's a way to modify our server to use MongoDB with the Mongoose package to store book objects.
Here is our complete working code:

First, make sure you have MongoDB installed and running on your machine.
Step 1: Install Mongoose
Install Mongoose using npm:
npm install mongoose

Step 2: Connect to MongoDB
Start by importing mongoose, then use the mongoose.connect function to connect to your MongoDB database. You typically run your MongoDB database on your localhost at port 27017, and then specify the name of your database ('bookdb' in this example):
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/bookdb', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Successfully connected to MongoDB'))
.catch(err => console.error('Connection error', err));

Step 3: Define a Schema
The schema defines the shape of the documents within a collection.
Just like the TABLE definitions in a SQL database.
Create a bookSchema that corresponds to your book data:
const bookSchema = new mongoose.Schema({
id: String,
title: String,
author: String
});

Step 4: Compile the Schema into a Model
A model is a constructor compiled from the Schema.
An instance of a model represents a document in the database:
A document is anagolous to a ROWSET in a SQL Table.
const Book = mongoose.model('Book', bookSchema);
The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural, lowercase version of your model name in your MongoDB database, so a model named Book maps to the 'books' collection in the database.
Step 5: Replace your Array Operations with Mongoose Methods
Now, we'll replace the array operations in your Express routes with Mongoose methods:
app.get('/books', (req, res) => {
Book.find()
.then(books => res.json(books))
.catch(err => res.status(500).send(err));
});

app.post('/books', (req, res) => {
const newBook = new Book(req.body);
newBook.save()
.then(() => res.status(201).send(newBook))
.catch(err => res.status(500).send(err));
});

app.put('/books/:id', (req, res) => {
Book.findByIdAndUpdate(req.params.id, req.body)
.then(() => res.send())
.catch(err => res.status(404).send(err));
});

app.delete('/books/:id', (req, res) => {
Book.findByIdAndRemove(req.params.id)
.then(() => res.send())
.catch(err => res.status(404).send(err));
});

Full Code:
Here's the complete version of your server, now using Mongoose and MongoDB to persist data:
javascriptCopy code
const express = require('express');
const mongoose = require('mongoose');

const app = express();
app.use(express.json());

mongoose.connect('mongodb://localhost:27017/bookdb', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Successfully connected to MongoDB'))
.catch(err => console.error('Connection error', err));

const bookSchema = new mongoose.Schema({
id: String,
title: String,
author: String
});

const Book = mongoose.model('Book', bookSchema);

app.get('/', (req, res) => {
res.send('Hello World!');
});

app.get('/books', (req, res) => {
Book.find()
.then(books => res.json(books))
.catch(err => res.status(500).send(err));
});

app.post('/books', (req, res) => {
const newBook = new Book(req.body);
newBook.save()
.then(() => res.status(201).send(newBook))
.catch(err => res.status(500).send(err));
});

app.put('/books/:id', (req, res) => {
Book.findByIdAndUpdate(req.params.id, req.body)
.then(() => res.send())
.catch(err => res.status(404).send(err));
});

app.delete('/books/:id', (req, res) => {
Book.findByIdAndRemove(req.params.id)
.then(() => res.send())
.catch(err => res.status(404).send(err));
});

app.listen(3001, () => console.log('Server running on port 3001'));

This code is a starting point. In a full-featured app, you'd want to add more error checking, validation, etc. Also, in a real-world situation, you would not expose your database directly to the client as we're doing here. Instead, you'd probably have a separate API layer, and the client would make requests to that API, which would then interact with the database.

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.