3 WAYS OF DATA INSERTION IN NODEJS

 

How to add Data Using Nodejs ……..??

To add data to a MongoDb Collection, we must first make the data available as Key-value pairs, which is similar to JSON format, because MongoDB accepts JSON data to be added into it. Nodejs can insert data into a MongoDb collection in three ways. Some of the methods  

·       We can create a data object with a single value

·       We can make a data Array with many data objects.  

·       We can accept dynamic input from the user (postman is used here).

This article will go over all three methods for putting data into a MongoDB Collection using Nodejs.  

Prerequisites:-

To begin, we need a better understanding of how to design a Model, which is a fundamental building element. For additional information, see our earlier blog post on Create a Model in Nodejs, where we constructed a usersModel with the necessary fields and data types. We may reuse the same userModel to populate the users collection with data. 


Real-time Implementation:-

Referring to my Previous Blog on Nodejs Application Folder Structure, let us create the required js files in the corresponding folder as given in the below picture.



We will try to connect to the Database with Mongoose library. To proceed further, open the terminal in the workspace and run the following commands npm i mongoose & npm i dot-env. These commands will install the required dependencies in the workspace.

 

Create a file named connection.js in the “bin” folder, and add the below lines of code

// importing mongoose library
// install mongoose  -- (npm i mongoose)
const mongoose = require("mongoose");
// install dotenv library using npm -- (npm i dotenv)
require("dotenv").config();

// using mongoose connect method to connect to database
// process.env.DB_URL - is the database details retrieved from .env file
mongoose
  .connect(process.env.DB_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log("Connected to Database");
  });

Next create a file userController.js in the Controller folder. This class defines the business logic useful for performing a particular operation. It is always recommended to write the piece of code in the try/catch blocks. As we discussed above, we are going to add User Data into the User Collection in 3 different ways.

1. Adding a single value:-

// import the userModel from the models folder
// to perform the Db operations
const userRepo = require("../models/userModel");

// writing a method to add a user
exports.addNewUser = async (req, res) => {
  try {
    // adding a single user data to users Collection in mongoDB
    const singleUserObj = {
      name: "Harsha", // String
      emailId: "harsha@gmail.com", // String
      mobile: 9876543210, // Number
      dateOfBirth: "2023-05-28T00:00:00.000Z", // Date
    };

    // add single user
    const addUser = await userRepo
      .create(singleUserObj)
      .then(() => {
        console.log("Added user info to users Collection");
      })
      .catch((e) => {
        e = new Error("User details already exists");
        throw e;
      });

   
    if (addUser !== "" || addUser !== null) {
      res.status(200).json({
        status: "success",
        data: addUser,
      });
    } else {
      res.status(400).json({
        status: "failed",
        message: "Unable to add new user",
      });
    }

    console.log("details of the new User:- " + addUser);
  } catch (err) {
    res.status(400).json({
      status: "failed",
      message: err.message,
    });
  }
};

2. Adding multiple values at a time:-

// import the userModel from the models folder
// to perform the Db operations
const userRepo = require("../models/userModel");

// writing a method to add a user
exports.addNewUser = async (req, res) => {
  try {
    // adding Multiple users to the users Collection
    const multiUserObj = [
      {
        name: "Harsha", // String
        emailId: "harsha@gmail.com", // String
        mobile: 9876543210, // Number
        dateOfBirth: "2023-05-28T00:00:00.000Z", // Date
      },
      {
        name: "Vardhan", // String
        emailId: "vardhan@gmail.com", // String
        mobile: 1234567889, // Number
        dateOfBirth: "2023-06-23T00:00:00.000Z", // Date
      },
    ];

    // add multiple users
    const addUser = await userRepo
      .create(multiUserObj)
      .then(() => {
        console.log("Added user info to users Collection");
      })
      .catch((e) => {
        e = new Error("User details already exists");
        throw e;
      });

    if (addUser !== "" || addUser !== null) {
      res.status(200).json({
        status: "success",
        data: addUser,
      });
    } else {
      res.status(400).json({
        status: "failed",
        message: "Unable to add new user",
      });
    }

    console.log("details of the new User:- " + addUser);
  } catch (err) {
    res.status(400).json({
      status: "failed",
      message: err.message,
    });
  }
};

3. Dynamic Inputs from User:-

// import the userModel from the models folder
// to perform the Db operations
const userRepo = require("../models/userModel");

// writing a method to add a user
exports.addNewUser = async (req, res) => {
  try {
    // adding a user in Runtime to users collection via postman
    const addUser = await userRepo
      .create(req.body)
      .then(() => {
        console.log("Added user info to users Collection");
      })
      .catch((e) => {
        e = new Error("User details already exists");
        throw e;
      });

    if (addUser !== "" || addUser !== null) {
      res.status(200).json({
        status: "success",
        data: addUser,
      });
    } else {
      res.status(400).json({
        status: "failed",
        message: "Unable to add new user",
      });
    }

    console.log("details of the new User:- " + addUser);
  } catch (err) {
    res.status(400).json({
      status: "failed",
      message: err.message,
    });
  }
};

In all the above 3 varieties we have followed some common code structure as follows:-

·       Imported the usermodel from the models folder, to perform Database related operations

  • As we know Nodejs follows an Asynchronous programming structure, we have declared an asynchronous function (addNewUser) to add data to the database.
  • We are using exports because this function can be reused in other files if required
  • All the data which we are inserting as a single object or Multiple objects are defined in Key Pair values.
  • The structure of a single data object is defined in ‘{ }’, and for the multiple objects ‘[{ }]’ we are defined in an array, for the dynamic inputs from the user we can we single object notation or the array notation, based on the requirement and can be passed from POSTMAN.
  • The req.body defines the data coming in the request to be inserted into the database.
  • We are using userRepo.create to insert the data into the User Collection. And we have used the .then and .catch functions to handle the error that occurred in the Mongoose function call.

res.status(200).json({
        status: "success",
        data: addUser,
      });

In the above lines of code, we are returning the responses to the client. With the status code, status value, and the data required.

We are done with Coding for the requirement of adding a user to the User Collection in the Database. But how can we add data into database, to do that we need a router which can help us to accomplish the task. The router is a API, which acts as intermediate linkage between the client and the server to carry the request payloads and the responses to the respective locations.

Create a userRouter in the routes folder, with the below code. We need to install express as – (npm i express)

// import express library
const express = require('express');
// import the userController from the controllers folder
// to perform the routing operations
const userController = require('../controllers/userController');

const router = express.Router();

// post api call
router.post('/adduser', userController.addNewUser);

// exporting for re-usage of this class in other areas
module.exports = router;

To complete the required operation of adding a user to the mongo Collection, we need to configure this route in the app.js file, which is the root file of the Nodejs project.

The code of app.js file:-

const express = require('express');
const bodyParser = require('body-parser');
const userRoute=require('./routes/userRoutes');

const app = express();
require('dotenv').config();
require('./bin/connection.js');

app.use(bodyParser.json());
app.use('/user', userRoute);

const port = process.env.PORT;
app.listen(port, () => {
  console.log(`App running on port ${port}...`);
});


We will be discussing the contents of app.js file, in upcoming blogs. We can see the add user operation from Postman (sending requests and getting back response), with the dynamic user input.


To hit any URL from postman, we need to start out Backend webserver using npm start, as below



Api with Request Payload:-


 

Response Received for the above:-



Harsha Vardhan Garlapati

As a software engineer and technology enthusiast, I thrive on exploring the ever-evolving world of technology and leveraging it to create innovative solutions. With a passion for sharing knowledge and insights, I also delve into the world of blogging to inspire and educate others in the realm of software development. Beyond the realm of code, I find joy in exploring new destinations as a passionate traveler, embracing diverse cultures, and broadening my horizons. In my free time, I cherish moments spent with friends, valuing the connections and experiences that enrich my life. Combining my technical expertise, love for writing, adventurous spirit, and the importance of human connections, I aim to leave a positive impact on the world through my work, experiences, and interactions. Let’s embark on this exciting journey together, exploring the wonders of technology while cherishing the moments that truly matter.

Post a Comment

Previous Post Next Post