-->

  • How to make Post API with mongoose in Nodejs

     

    Disclaimer   All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.

     

    Make Post API with mongoose in Nodejs



    This blog we have seen mongodb basic and how is it work with installation and after installation, we have already seen mongodb basic, CRUD operation, connect mongodb with nodejs, read, update, delete, POST, GET API etc. we should not face any problem while making Database, collection(table) and using the data in nodejs even whenever we will make API. Read data from mongodb in nodejs



    • # What is Mongoose
    • # Install Mongoose
    • # Make Config file for MongoDB
    • # Make Post Route
    • # Get data from the postman and save in DB


     

    Now in this blog  we will use mongoose. There is an npm package to connect nodes to mongodb. Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. They created mongoose by improving mongodb, with the help of which you can create schemas and models of mongoose's movements.

    Suppose that there are 4 fields in our database (like name, brand, price, category) and the user wants to add a 5th field also (like color) but we want to add only 4 fields, for this we create schemas.

    Here you can also define TYPE in schemas like price type is numeric but if any user wants to use quotes (" " ' ') then we can stop the user for this.

    in sort we can apply validation in mongoose but we can't in directly mongodb.

     

     

     What is MongoDB

     

    MongoDB is a popular open-source NoSQL (non-relational) database management system. NoSQL means no structure like it is look like an object while in SQL it is a structure query language like SELECT CustomerName, City FROM Customers; (The SELECT statement is used to select data from a database.) But NoSQL database is useless...NOT completely because of whenever we want add extra column in database then it is possible through NoSQL MongoDB.   

     

    MongoDB installation - CLICK HERE

    MongoDB Basic Command - CLICK HERE

    About MongoDB vs SQL - CLICK HERE

    CRUD in MongoDB - CLICK HERE

     

     



    Object Like - 

     

     

    {
      "_id": {
        "$oid": "659ad46e0382148123c82841"
      },
      "name": "moto G60",
      "brand": "motorola",
      "price": 16500,
      "category": "mobile"
    }
    
    
    

     

     


    MongoDB is a type of database that helps store and manage large amounts of data in a flexible and scalable way. Unlike SQL, MongoDB doesn't require a fixed structure for the data, allowing you to store information in a more versatile format.


    • MongoDB is a NoSQL database.
    • The data stored in a collection
    • Collection don't have row and columns
    • Data is stored in the form of object.




    Install Mongoose


    For this you need to copy this (npm i mongoose) and paste it in project's terminal.

    https://www.npmjs.com/package/mongoose

     

     

    Disclaimer   All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.

     

     

    config.js

     

    First of all we will create a new file called as config.js and inside this file we will make connection code of mongodb and add a database name.



    const mongoose = require('mongoose');
    mongoose.connect("mongodb://127.0.0.1:27017/e-comm");
    
    
    

     

    Simply you can copy the "mongodb://127.0.0.1:27017/" from mongodb and e-comm is our database name.

     

     

    Product.js

     

    Now we can create product scheme code inside of product.js file. we have already told about schema and model.  you can check our previous tutorial.

     

     

    const mongoose = require('mongoose')
    const ProductScheme = new mongoose.Schema({
        name: String,
        brand: String,
        price: Number,
        category: String
    });
    
    
    module.exports = mongoose.model('products', ProductScheme );
    

     

     

    Here we will describe each line of code don't worry. first import the mongoose and create a ProductScheme and inside this scheme we will add from mongodb parameter that we have already used like name, brand, price, category and export with module.exports = mongoose.model('products', ProductScheme);



    index.js


    Here we go with route and create a '/create' route  and import config.js and product scheme.

     

     

    const express = require('express')
    require('./config')
    
    const product = require('./product');
    
    const app = express();
    
    app.post('/create', async (req, resp) => {
         resp.send('Done')
    })
    
    app.listen(8000)
    
    

     


    Let's breakdown the code -

     

    1) importing express

    const express = require('express');


    This line imports the Express.js framework, which simplifies the process of creating and managing a web server in Node.js.



    2) Loading Configuration:

    require('./config');


    This line seems to be importing a configuration file (presumably named 'config.js' or similar). This file may contain settings, environment variables, or any other configuration needed for the application.



    3) Importing 'product' Module:

    const product = require('./product');


    This line imports the 'product' module. The exact purpose of this module is not clear from the provided code, as it's not being used in the routes. It could be handling product-related functionality.



    4) Creating an Express Application:

    const app = express();


    This line creates an instance of the Express application, which is used to configure and define routes for your web server.



    5) Defining a POST Route:


    app.post('/create', async (req, resp) => {
        resp.send('Done');
    });



    This code sets up a route for handling HTTP POST requests to the '/create' endpoint. When a POST request is made to '/create', the server responds with the text 'Done'. The route handler is an asynchronous function, indicated by the async keyword.



    6) Starting the Server:


    app.listen(8000);




    This line starts the Express application on port 8000. The server will listen for incoming HTTP requests on this port. You can access the server by navigating to http://localhost:8000 in a web browser.




    Run with nodemon cmd


    Disclaimer   All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.



    Now in this postman we will add json data in body section and send the data via postman but we will add two line of code.



    app.use(express.json())
    
    
       console.log(req.body)
    




    Here req.body we want to console (output) but when data is coming in req.body section before that convert into json format that's why we have to use app.use(express.json()).

     

     

    Disclaimer   All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.






    Now we will store the data in mongodb database.

     

       let data = new Product(req.body)
       let result = await data.save();
       console.log(result)
       resp.send(result)
       
    
    

     

    Here, we will add new keyword with (req.body) and data save in DB so data.save(); and it's return the promise thats why we will await async. Finally we will get output.

     

     

    Disclaimer   All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.

     

     

    Disclaimer   All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.

     

     



    Disclaimer



    All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.

     


  • 0 comments:

    Post a Comment

    For Any Tech Updates, Hacking News, Internet, Computer, Technology and related to IT Field Articles Follow Our Blog.