The best way to Integrate the Node JS Application with MongoDB
The best way to Integrate the Node JS Application with MongoDB
01 July 2021
Introduction
- In this article you are going to learn about how to integrate a MongoDB database with an existing Node application.
- Node.js has the ability to work with both MySQL and MongoDB as databases.
- Before reading this article we have required basic knowledge of the Node JS platform.
Node JS: MongoDB Setup
Install the NodeJS mongoDB module by using the NPM (Node Package Manager).
$ npm install -g mongodb
Options
- “-g” : Install this package globally
- “Mongodb” : Install Node JS MongoDB module.
Verify the MongoDB successfully installed
- Enter the following command on your command prompt.
$ mongo
- This will drop you into an administrative shell.
Adding Mongoose and Database Information to the Project
Add the npm package mongoose to the project with the npm install command:
$ npm install mongoose
- Mongoose gives you the built-in methods, which you will use to create the connection to your database.
- Before creating your mongoose schemas and model you need to make connections with the database. We will add our database connection information to our application.
- Create one file database_info.js inside the project.
- Add the following constants in the database_info.js file
- ‘mongoose’ give you access to Mongoose’s built-in methods
const mongoose = require('mongoose'); const MONGO_DB_USERNAME = 'sandip; const MONGO_DB_PASSWORD = '1234'; const MONGO_DB_HOSTNAME = '127.0.0.1'; const MONGO_DB_PORT = '27017'; const MONGO_DB = 'studentInfo';
Add the DB connection information to the App.js file so that the application can use it.
const express = require('express'); const app = express(); const router = express.Router(); const path = __dirname + '/views/'; const router = express.Router(); const db = require('./database_info); const path = __dirname + '/views/';
How to create Mongoose Schemas and Models
- Create the ‘modules’ directory inside your project.
- Add the ‘Student.js’ model inside the models folder
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const Student = new Schema ({ email: { type: String, required: true }, character: { type: String, required: true }, }); module.exports = mongoose.model('Student', Student)
- Imported the ‘mongoose’ at the top line
- Schema object is defined in the second line.
- Defined the fields which are required in the schema
- In the last line, We need to call the model constructor on the Mongoose instance and pass it the name of the collection and a reference to the schema definition.
- You can also make the email attribute unique, required by using the following options
let emailSchema = new mongoose.Schema({ email: { type: String, required: true, unique: true, lowercase: true, validate: (value) => { return validator.isEmail(value) } } })
- Add the validation function that will ensure that the value is a valid email address.
Basic Operations on MongoDB
Create the controller to perform the operations:
nano controllers/studentController.js
Create Operation:
Create function used to create the document in the DB
exports.create = function (req, res) { var student = new Student(req.body); student.create(function (err) { if(err) { console.log(“Failed to create”); } else { console.log(“Create Successfully..!!”); } }); };
Fetch All Records:
Find command is used to fetch all the records
exports.list = function (req, res) { Student.find({}).exec(function (err, res) { if (err) { console.log(“Failed to fetch”); } else { console.log(“Records fetched”); } ); }); };
Mongoose has a very rich API set that handles many complex operations supported by MongoDB.
StudentModel.find() .skip(100) .limit(10) .sort({firstName: 1} .select({firstName: true} .exec() .then(docs => { console.log(docs) }) .catch(err => { console.error(err) })
- find: Find all users
- skip : Skip the first 100 records
- limit: Limit the results to 10 records
- sort: Sort the results by the firstName field
- select: Select the firstName
- exec : Execute the query
Reference
- https://www.journaldev.com/8522/integration-of-node-js-and-mongodb-simple-example#introduction-to-node-js-and-mongodb
- https://www.digitalocean.com/community/tutorials/how-to-integrate-mongodb-with-your-node-application
- https://www.freecodecamp.org/news/introduction-to-mongoose-for-mongodb-d2a7aa593c57/