e.preventDefault(); // Prevent form submission input.blur(); // remove focus input.value = ""; // optional: clear the input

The best way to Integrate the Node JS Application with MongoDB

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

Related Posts

Latest Posts

  • All Posts
  • Generative AI
  • manufacturing
  • News
  • Portfolio
    •   Back
    • Android
    • iOS
    • Java
    • PHP
    • MEAN
    • Ruby
    • DotNet
    • IoT
    • Cloud
    • Testing
    • Roku
    • CMS
    • Python

India

Plot No. 11/2, Phase 3, Hinjewadi Rajiv Gandhi Infotech Park, Pune, India – 411057.
info@tudip.com
+91-96-8990-0537

United States

1999 S. Bascom Ave Suite 700, Campbell CA. 95008, USA.
info@tudip.com
+1-408-216-8162

Canada

64 Caracas Road North York, Toronto Ontario M2K 1B1, Canada.
info@tudip.com

Mexico

Calle Amado Nervo #785 Interior B Colonia Ladron De Guevara 44600 Guadalajara, Jalisco, Mexico.
info@tudip.com

Colombia

Cra. 9 # 113-53 Of. 1405 Bogotá D.C., Colombia.
info@tudip.com

UAE

Tudip Information Technologies L.L.C Office No 109, ABU HAIL BUILDING 13, Abu Hail, Dubai, UAE.
info@tudip.com

Nigeria

22 Kumasi Crescent, Wuse 2, Abuja, Nigeria.
info@tudip.com