mongoose Tutorial
Introduction
Mongoose is an Object Modeling Library(ODM). It is heavily used with nodejs when MongoDB is there. One main advantage is that it provides abstraction. MongoDB is schema-less but with mongoose, the developers can define a schema. It overcame the one main problem. Moreover, MongoDB methods can easily be used in mongoose. Another important feature of mongoose is validations. Several other features such as plugins, middleware, population, etc came with it. In this article, we will discuss a simple mongoose tutorial.
Prerequisites
Before we start, we need the following requirements.
- NodeJs and MongoDB installed.
- Knowledge of Node Package Manager(NPM)
- Knowledge of javascript
- Nodemon installed
- An IDE
Creating server
Let’s begin. First of all, we need a package.json file to start with. Create a new folder and name it anything you like. I will name it “newApp”. Open a terminal and go to this folder. Then, run the following command. You can omit -y if you want to provide details in the package.json file.
1 | npm init -y |
This command will create a package.json. Next, we need express.js. It is a web framework for NodeJs. Run the following command to install express.
1 | npm install express |
Let’s create a server now. In the same folder, create a new file and name it “server.js” and paste the following code in it.
1 2 3 4 5 6 7 8 9 | const express = require('express'); const app = express(); const port = 4000 app.listen(port, function() { console.log("Server is running on Port: " + port); }); |
In the above code, we imported express and used it to create a server. Let’s run it using the nodemon.
The server is running.
Connection with MongoDB
Let’s connect MongoDB with it. We will create two APIs – One will insert the data and the other will retrieve it. But first, we need a connection with MongoDB. To establish a connection, install the mongoose ODM.
1 | npm install mongoose |
This will install MongoDB successfully. Now we can use mongoose to establish a connection with MongoDB. Insert the following code into the server.js file.
1 2 3 4 5 6 7 8 9 10 11 | const mongoose = require('mongoose'); var uri = 'mongodb://localhost:27017/details' mongoose.connect(uri,{ useUnifiedTopology: true, useNewUrlParser: true}) const connection = mongoose.connection connection.once('open', function() { console.log("MongoDB database connection established successfully"); }) |
In the above code, we imported mongoose and then create a uri. The following is the uri.
1 | var uri = 'mongodb://localhost:27017/details' |
The name of the database which we connecting to is “details”. Next, we used the connect() method for the connection. Let’s run it to check if the connection is successful or not.
The connection is successful!
Schema
The next step is to create a schema. The documents in the database will be inserted according to the schema we will define. In the same folder, create a new file and name it “model.js”. Paste the following code in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | const mongoose = require('mongoose'); const Schema = mongoose.Schema; let employee = new Schema( { name: { type: String }, age : { type: Number }, location :{ type: String } }, { collection: 'Employees' } ); module.exports = mongoose.model('employees', employee); |
This is the schema. The name of the collection is Employees and each document in this collection will hold three fields – name, age, and location. We also exported the schema at the end of the file because we need it inside the server.js file. Let’s import this into the server.js file.
1 | const employees = require('./model') |
Router
Before moving to APIs, we need a router to create route handlers. Add the following code in the server.js file.
1 2 3 | const router = express.Router() app.use('/', router); |
Any link, starting with ‘/’ will be captured by the router we created. This is how server.js file looks like now.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | const mongoose = require('mongoose'); const express = require('express'); const app = express(); const employees = require('./model') const router = express.Router() const port = 4000 var uri = 'mongodb://localhost:27017/kennel' mongoose.connect(uri,{ useUnifiedTopology: true, useNewUrlParser: true}) const connection = mongoose.connection connection.once('open', function() { console.log("MongoDB database connection established successfully"); }) app.use('/', router); app.listen(port, function() { console.log("Server is running on Port: " + port); }); |
We used Nodejs and express.js to create a server. Then we established a connection with MongoDB using mongoose. Using mongoose again we created a schema for our collection and at last, we defined a router. Let’s create APIs now.
APIs
The first API will insert data into the Employees collection. So the router handler will make a post request.
1 2 3 4 | router.route('/insertdata').post(function(req,res){ }) |
The above route handler will be invoked when the endpoint ‘/insertdata’ is executed.
There are couple of methods that can be used to insert data into a collection. We will use the insertMany() method. The insertMany() method takes an array of objects as its parameter. We will insert three documents in the Employees collection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | var data = [ { "name" : "John", "age" : 21, "location" : "New York" }, { "name" : "Smith", "age" : 27, "location" : "Texas" }, { "name" : "Lisa", "age" : 23, "location" : "Chicago" } ] |
The model we imported earlier will be used to invoke the insertMany() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 | employees.insertMany( data, function(err, result){ if(err){ res.send(err) } else{ res.send(result) } }) |
We passed the array to the insertMany() method. Place the above in the route handler we created earlier.
Let’s use the postman tool to test this endpoint.
The insertMany() method returns the documents that were inserted successfully in the collection.
Similarly, we can create another route handler to fetch the documents. The difference here will be – Instead of the POST method, we will make the GET method and instead of insertMany() method, we will use the find() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | router.route('/fetchdata').get(function(req,res){ employees.find( {}, function(err, result){ if(err){ res.send(err) } else{ res.send(result) } }); }) |
Let’s execute the route using the postman tool.
Yes! It returns all the documents.
Conclusion
So this was a simple tutorial about how to use mongoose. In this application, we created a server using express and nodejs. We used mongoose to establish a connection with MongoDB. The mongoose is also used to create the schema. For routing, we used express.js and then, we create two APIS – one for inserting and fetching data.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started