Posted by Abhishek on April 22, 2020
Important: Before you start reading this blog, I strongly urge you to read the Backend with NodeJS - Part 1 blog so that you will better understand the context.
As you are aware, the criminal information is currently stored in-memory within the codebase. This is not desired from a real-world perspective. In this blog, we will persist the criminal information in MongoDB rather than managing it in-memory.
mongoose
package
npm i mongoose
const mongoose = require('mongoose');
mongoose
.connect('mongodb://localhost/criminals')
.then(() => console.log('Connected to database...'))
.catch((err) => console.log('Connection to database failed.', err));
Create the schema of the Criminal object [this is like the table/document definition] and register the schema to the model class
const criminalSchema = mongoose.Schema({
name: {
type: String,
},
type: {
type: String,
},
});
const Criminal = mongoose.model('Criminal', criminalSchema);
Modify the GET()
and POST()
implementations by referencing the Criminal
model class
app.get('/api/criminals', async (req, res) => {
res.send(await Criminal.find());
});
app.post('/api/criminals', async (req, res) => {
const newCriminal = new Criminal({
name: req.body.name,
type: req.body.type,
});
const result = await newCriminal.save();
res.send(result);
});
http://localhost:3000/api/criminals
, you should get an empty array as response.http://localhost:3000/api/criminals
with the request body as shown below. You should get the response back with the created criminal record that has an id
value. This confirms that POST is working.
http://localhost:3000/api/criminals
and you should see the newly created criminal record being shown in the response.
Just to make sure that this record is persisted in MongoDB, we can check the record using MongoDB Compass.
In the next blog, we will structure this project in a much better way rather than having everything written in app.js. Stay tuned…