How to Insert Data into MongoDB Using Mongoose and Node.js

Mongoose is the best solution to insert data into MongoDB.Because It is very easy & fast. So, In this tutorial, you will get the best script with an example to insert form data in Node.js Express. Even you will learn it with MVC pattern using express. Therefore, It is simple to understand & implement in your project.

It is explained with the simple HTML form that has four input fields like Full Name, Email Address, City & address. This example will help you to implement another form of information.

insert data into mongodb using mongoose and node.js

From the next step, you will learn How to insert data into MongoDB using Mongoose. So, read the complete steps and share with your friends too those who are interested to learn it.

Insert Data into MongoDB Using Mongoose & Express

Before getting started, you must configure the following basic steps

  • Install Node.js on your device
  • Install MongoDB Community Server
  • Also, Install MongoDB Compass  and create a Database with the name nodeapp & Collection with the name users

1. Install Express Application

First, Install Express Application and Create the following necessary folders & files

  |     |__user-controller.js
  |     |__user-model.js
  |     |__user-route.js
  |     |__user-form.ejs

2. Connect Node.js App to MongoDB Database

You must connect Node.js App to MongoDB Database with the help of the following script.

File Name – database.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/nodeapp', {useNewUrlParser: true});

var conn = mongoose.connection;

conn.on('connected', function() {
    console.log('database is connected successfully');
    console.log('database is disconnected successfully');

conn.on('error', console.error.bind(console, 'connection error:'));

module.exports = conn;


3. Create a Model to Insert Data

Now, Create a model to insert data and configure the following points to write it’s the script –

  • Include mongoose module using require('mongoose')
  • Include MongoDB database using require('../database')
  • Create a schema userSchema with the collection columns’ name like first_name, email_address, city & country.
  • Pass the collection name users & schema userSchema to the mongoose module and assign it to a variable userTable
  • After that, Write a mongoose query withing module.exports to save data into the MongoDB Datable

Note – Name of Form Input Fields & collection column should be the same.

File Name –  insert-model.js

var mongoose=require('mongoose');
var db = require('../database');

// create an schema
var userSchema = new mongoose.Schema({
            full_name: String,

     createData:function(inputData, callback){
        userData= new userTable(inputData);, data){
          if (err) throw err;
           return callback(data);


4. Create an HTML Form to Insert Data

Create an HTML form with five input fields like Full Name, Email Address, City, Country & Submit. Also, the form must have the following two attributes –

  • method="POST"
  • action="/create".

File Name – user-form.ejs

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">

<!--====form section start====-->
<div class="user-detail">
    <form action="/create" method="POST">
          <label>Full Name</label>
          <input type="text" placeholder="Enter Full Name" name="full_name" required >
          <label>Email Address</label>
          <input type="email" placeholder="Enter Email Address" name="email_address" required>
          <input type="city" placeholder="Enter Full City" name="city" required>
          <input type="text" placeholder="Enter Full Country" name="country" required>
          <button type="submit">Submit</button>
<!--====form section start====-->


5. Create a Controller to Insert Data

Now, Create a controller to insert data with the help of the following points –

  • Include user module using require('../models/insert-model')
  • Create a method userForm to display the form in the browser
  • Also, create another method createData to save data on the form submit

File Name – insert-controller.js

var insertModel= require('../models/insert-model');
    createData:function(req, res){
         var inputData= req.body;
         insertModel.createData(inputData, function(data){
            console.log(" record was created");


6. Create a Router to Insert Data

Create a Router with the following two routes –

  • Create a route /user-form with the GET method to display the user form in the browser.
  • Also, create another route /create with the POST method to insert data
  • At last, export the router

File Name – insert-route.js

var express = require('express');
var router = express.Router();
var insertController= require('../controllers/insert-controller');

router.get('/user-form', insertController.userForm);'/create', insertController.createData);

module.exports = router;

7. Include Router in the app.js

You must include the following router code in the app.js.

File Name – app.js

var insertRouter = require('./routes/insert-route');

app.use('/', insertRouter);

In this file, You will get more lines of default code that play the most important role to run the node.js. So, you must not remove any line of them.

8. Run Node.js App to Insert Data

First of All, start the node.js server and enter the following URL in your browser.


My Suggestion

Dear developers, I hope you have understood the above script, Now you are able to insert data into MongoDB using Mongoose and Node.js express

I will share more tutorials on Node.js/Express asap. So, Continue to visit this website.

If you have any doubts or questions. You can directly ask me through the below comment box.