How to use Mongodb with express js - deesoft service

How to use Mongodb with express js

Deepak Tailor Image
Deepak Tailor - Dec 01 2021
How to use Mongodb with express js

mongodb is a database that is used extensively with nodejs. How to use this database with the Express Framework. How to insert data in database, how to read data and how to update and delete data.

1. Install mongoose ( npm install mongoose)

How to connect mongodb in express server

1. Import mongoose

2. Call connect function with pass db string

3. Then call connection function

4. If database is connected show “db connect” and some error then show “connection error” in console.

import mongoose from 'mongoose';

// connection mongodb
const DB_STRING = "mongodb://localhost:27017/demo";
mongoose.connect(DB_STRING, {useNewUrlParser :  true});
const con = mongoose.connection;
con.on('error', () => { console.log('connection error'); });
con.once('open', () => { console.log('db connect'); });
How to use Mongodb with express js
Create model file (create table)

In mongodb we do models. In which we tell which type of value to be saved in the column.

1. Import mongoose

2. Call schema method

import mongoose from 'mongoose';

// call schema method
const Schema = mongoose.Schema;

// create student schema
const studentSchema = new Schema({
    first_name : {type: String},
    last_name : {type : String },
    mobile_no : {type: Number},
    email_id : {type: String},
    password : {type : String}
});

export default mongoose.model('student', studentSchema);

after the complete schema then call model function for the create of model. First parameter pass (model name) and second parameter pass (schema).

Insert record in mongodb

How to insert body data into mongodb.

How to use Mongodb with express js
import student from './model';
create a new route for this request
router.post('/', async (req, res, next) => {

    // get row data in body
    const first_name    = req.body.first_name;
    const last_name     = req.body.last_name;
    const mobile_no     = req.body.mobile_no;
    const email         = req.body.email;
    const password      = req.body.password;

    try {
        const insertData = await student.create({
            first_name : first_name,
            last_name : last_name,
            mobile_no : mobile_no,
            email_id : email,
            password : password
        });
        return res.json({data : insertData});
    } catch (error) {
        return res.json({data : error.message});
    }
    
});
How to use Mongodb with express js
Insert multiple data into mongodb
[
	{
	    "first_name": "mohit",
	    "last_name": "tailor",
	    "mobile_no": "1234567890",
	    "email_id": "deepak@email.com",
	    "password": "123456"
	},
	{
	    "first_name": "rohit",
	    "last_name": "tailor",
	    "mobile_no": "1234567890",
	    "email_id": "rohit@email.com",
	    "password": "123456"
	},
	{
	    "first_name": "deepak",
	    "last_name": "tailor",
	    "mobile_no": "1234567890",
	    "email_id": "deepak@email.com",
	    "password": "123456"
	}
]
Insert multiple data with using insertMany function
router.post('/', async (req, res, next) => {

   try {
       const insertData = await student.insertMany(req.body);
       return res.json({data : insertData});   
   } catch (error) {
    return res.json({data : error.message});
   }

});
Fetch all data from database

url : http://localhost:3000

router.get('/', async (req, res, next) => {

    try {
        const allData = await student.find();
        return res.json({data : allData});   
    } catch (error) {
     return res.json({data : error.message});
    }

});
Fetch single data by id

url : http://localhost:3000/61a490279d5bb0e101ac8b6f

router.get('/:id', async (req, res, next) => {

    const id = req.params.id;
    try {
        const allData = await student.findById({ _id : id});
        return res.json({data : allData});   
    } catch (error) {
     return res.json({data : error.message});
    }

});
Update single data

url : http://localhost:3000/61a490279d5bb0e101ac8b6f

{
	"first_name": "MOHIT",
	"last_name": "TAILOR"  
}
router.put('/:id',  async (req, res, next) => {
    const id = req.params.id;
    const data = req.body;
    try {
        const insertData = await student.findOneAndUpdate({_id : id}, data);
        return res.json({data : insertData});   
    } catch (error) {
     return res.json({data : error.message});
    }
});
Delete single data by id

url : http://localhost:3000/61a490279d5bb0e101ac8b6f

router.delete('/:id', async (req, res, next) => {
    const id = req.params.id;

    try {
        const deleteData = await student.deleteOne({_id : id });
        return res.json({data : deleteData});   
    } catch (error) {
     return res.json({data : error.message});
    }
});
{
    "data": {
        "deletedCount": 1
    }
}
Delete all data in database
router.delete('/', async (req, res, next) => {
   
    try {
        const deleteData = await student.deleteMany();
        return res.json({data : deleteData});   
    } catch (error) {
     return res.json({data : error.message});
    }
});
{
    "data": {
        "deletedCount": 4
    }
}
Deepak Tailor Image
Deepak Tailor

My name is Deepak tailor as a fullstack developer. I have been in the IT industry (PHP, Nodejs, flutter) for the last 5 years. For professional and customize web development & app development, you can send inquiry on our email.
----
You can contact him at deepaktailor10@yahoo.in