Hello folks! Welcome back to a new edition of our tutorial on ExpressJS. In this tutorial guide, we will be studying about ExpressJS Database.
We keep receiving requests, but end up not saving them anywhere. We need a database to store the data. For this, we will make use of the NoSQL database called MongoDB.
In order to utilize Mongo with Express, we need a client API for node. There're multiple options for us, but for this lesson, we'll stick to mongoose. Mongoose is utilized for document Modeling in Node for MongoDB. For document modeling, we create a Model (identical to a class in document oriented programming language), and then we make documents using this Model (like we create documents of a class in OOP). Every of our processing is going to be executed on these "documents", then lastly, we will write these documents in our database.
We keep receiving requests, but end up not saving them anywhere. We need a database to store the data. For this, we will make use of the NoSQL database called MongoDB.
In order to utilize Mongo with Express, we need a client API for node. There're multiple options for us, but for this lesson, we'll stick to mongoose. Mongoose is utilized for document Modeling in Node for MongoDB. For document modeling, we create a Model (identical to a class in document oriented programming language), and then we make documents using this Model (like we create documents of a class in OOP). Every of our processing is going to be executed on these "documents", then lastly, we will write these documents in our database.
Setting up Mongoose
Now that you have installed Mongo, let us install Mongoose, the same way we've been installing our other node packages -
npm install --save mongoose
Before we start utilizing mongoose, we've to create a database making use of the Mongo shell. To create a new database, open your terminal and enter "mongo". A Mongo shell will start, enter the following code -
use my_db
A new database is going to be created for you. Whenever you open the mongo shell, it will default to "test" db and you will have to change to your database making use of the same command above.
To make use of Mongoose, we are going to need it in our index.js file and then connect to the mongodb service which is running on mongodb://localhost.
To make use of Mongoose, we are going to need it in our index.js file and then connect to the mongodb service which is running on mongodb://localhost.
var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db');
Now our app is connected to our database, let's create a new Model. This model will act as a collection in our database. To create a new Model, make use of the following code, before defining any route -
var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema);
The above code snippet defines the schema for a person and creates a Mongoose Mode Person.
READ: Express.js | Form Data
Saving Documents
Now, we'll create a new html form; this form will help you get the details of a person and save it to our database. To create the form, create a new view file known as person.pug in views directory with the following content -
html head title Person body form(action = "/person", method = "POST") div label(for = "name") Name: input(name = "name") br div label(for = "age") Age: input(name = "age") br div label(for = "nationality") Nationality: input(name = "nationality") br button(type = "submit") Create new person
Also include a new get route in index.js file to render this document -
app.get('/person', function(req, res){ res.render('person'); });
Output
Visit "localhost:3000/person" to check if the form is displaying the accurate output. Note that this is just the user interface(UI), it's not yet functional. The screenshot below shows how the form is displayed -
We will now define a post route handler at '/person' which will handle this request.
app.post('/person', function(req, res){ var personInfo = req.body; //Get the parsed information if(!personInfo.name || !personInfo.age || !personInfo.nationality){ res.render('show_message', { message: "Sorry, you provided worng info", type: "error"}); } else { var newPerson = new Person({ name: personInfo.name, age: personInfo.age, nationality: personInfo.nationality }); newPerson.save(function(err, Person){ if(err) res.render('show_message', {message: "Database error", type: "error"}); else res.render('show_message', { message: "New person added", type: "success", person: personInfo}); }); } });
In the above code snippet, if we receive any empty field or do not receive any field, we're going to send an error response. Whereas if we receive a well-formed document, then we create a newPerson document from Person model and save it to our Database using the newPerson.save() function. This is defined in Mongoose and it accepts a callback as an argument. This callback has two arguments - error and response. These arguments will render the show_message view.
To show the response from this route, we'll also need to create a show_message view. Create a new view with the following code -
To show the response from this route, we'll also need to create a show_message view. Create a new view with the following code -
html head title Person body if(type == "error") h3(style = "color:red") #{message} else h3 New person, name: #{person.name}, age: #{person.age} and nationality: #{person.nationality} added!
Output
We are going to get the following response on submitting the form(show_message.pug) successfully -
We now have an interface to create persons.
Retrieving Documents
Mongoose makes available many functions for retrieving documents, we will focus on 3 of those. All these functions also accepts a callback as the last parameter, and just like the save function, their arguments are error and response. The following below are the three functions -
Model.find(conditions, callback)
Model.find function finds all the documents matching the field in conditions object. The same operators used in Mongo also works in mongoose. For example.
Person.find(function(err, response){ console.log(response); });
This's going to fetch all the documents from the person's collection.
Person.find({name: "Bethel", age: 28}, function(err, response){ console.log(response); });
This is going to fetch all documents where field name is "Bethel" and age is 28.
We can also provide projection we need i.e., the fields we need. For example, if we want only the names of people whose nationality is "Nigerian", we use -
We can also provide projection we need i.e., the fields we need. For example, if we want only the names of people whose nationality is "Nigerian", we use -
Person.find({nationality: "Nigerian"}, "name", function(err, response){ console.log(response); });
Model.findOne(conditions, callback)
This function always fetches a single, most applicable document. It has the same exact arguments as Model.find().
Model.findById(id, callback)
This function takes in the id (that is defined by mongo) as the first argument, an optional projection string and callback to handle the response. For example,
Person.findById("507f1f77bcf86cd799439011", function(err, response){ console.log(response); });
Let us now create a route to view all people records.
var express = require('express'); var app = express(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema); app.get('/people', function(req, res){ Person.find(function(err, response){ res.json(response); }); }); app.listen(3000);
READ: Express.js | Templating
Updating Documents
Mongoose offers three functions to update documents. The three functions are given below -
Model.update(condition, updates, callback)
This function takes a condition and updates an object as input and applies the changes to all the documents matching the condition in the collection. For example, the following code will update the nationality "American" in all Person documents -
Person.update({age: 25}, {nationality: "American"}, function(err, response){ console.log(response); });
Model.findOneAndUpdate(condition, updates, callback)
This function finds one document based on the query and updates that according to the second argument. It also takes a callback as last argument. Let us perform the following example to understand this function.
Person.findOneAndUpdate({name: "Bethel"}, {age: 40}, function(err, response) { console.log(response); });
Model.findByIdAndUpdate(id, updates, callback)
Model.findByIdAndUpdate function updates a single document that is identified by its id. For example,
Person.findByIdAndUpdate("507f1f77bcf86cd799439011", {name: "James"}, function(err, response){ console.log(response); });
Let us create a route that is going to update people. This'll be a PUT route with the id as a parameter and details in the payload.
var express = require('express'); var app = express(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema); app.put('/people/:id', function(req, res){ Person.findByIdAndUpdate(req.params.id, req.body, function(err, response){ if(err) res.json({message: "Error in updating person with id " + req.params.id}); res.json(response); }); }); app.listen(3000)
To test this route, enter the following in your terminal (replace the id with an id from your created people) -
curl -X PUT --data "name = James&age = 20&nationality = American "http://localhost:3000/people/507f1f77bcf86cd799439011
This'll update the document associated with the id provided in the route withh the details above.
Deleting Documents
We have covered, Create, Read and Update, now we're going to see how Mongoose can be used to Delete documents. We've three functions, exactly like update.
Model.remove(condition, [callback])
This function accepts a condition object as input and removes all documents matching the given condition. For example, if we need to remove all people aged 21, use the below syntax -
Person.remove({age:21});
Model.findOneAndRemove(condition, [callback])
Model.findOneAndRemove function removes a single, most relevant document according to conditions object. Now let us execute the following code to understand the same.
Person.findOneAndRemove({name: "Bethel"});
Model.findByIdAndRemove(id, [callback])
Model.findByIdAndRemove method removes a single document identified by its id. Below is a simple example -
Person.findByIdAndRemove("507f1f77bcf86cd799439011");
Let us now create a route to delete people from our database.
var express = require('express'); var app = express(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema); app.delete('/people/:id', function(req, res){ Person.findByIdAndRemove(req.params.id, function(err, response){ if(err) res.json({message: "Error in deleting record id " + req.params.id}); else res.json({message: "Person with id " + req.params.id + " removed."}); }); }); app.listen(3000);
To check the output, use the following curl command -
curl -X DELETE http://localhost:3000/people/507f1f77bcf86cd799439011
This's going to remove the person with the given id producing the following message -
{message: "Person with id 507f1f77bcf86cd799439011 removed."}
This concludes how we can create simple CRUD applications making use of MongoDB, Mongoose and Express. To further explore Mongoose, read the API docs.
Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we are going to be studying about ExpressJS Cookies.
Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.
Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.
Thanks for reading and bye for now.
Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.
Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.
Thanks for reading and bye for now.