Node Js Insert Document in MongoDB Collection Tutorial

Last updated on: by Digamber

You may have heard a lot about the term “MongoDB Document and Collection” before. This is a simple term that refers to the database when you are working with MongoDB. You can store as many as records or in your MongoDB database.

This straightforward article will briefly describe how to insert the document (data or record) in MongoDB collection using the Node js and Express, Mongoose and Bootstrap UI framework.

We will surely give you detailed information on setting up a basic Node js app from start to finish.

To add the data in the MongoDB database through the Node js platform requires certain modules and packages.

We will install the Mongoose, ejs, express-flash, express-session, body-parser, express-validator, and cors packages from the NPM registry.

How to Add Record or Document in MongoDB Collection using Node Js and Mongoose

  • Step 1: Create Node Project
  • Step 2: Install NPM Dependencies
  • Step 3: Connect to MongoDB
  • Step 4: Build Schema with Mongoose
  • Step 5: Define Routes with Express
  • Step 6: Create Form to Add Records
  • Step 7: Build Server File
  • Step 8: Serve Node Application

Set Up Node App

Type and execute the provided command to make a blank directory for node app.

mkdir node-crud

Now, go into the app folder.

cd node-crud

A package.json file is essential for building a node-based application; It allows us to keep records of additional information about scripts, packages and project metadata.

npm init

Add Essential Modules

On to the terminal, paste the provided commands, execute these commands respectively to add the essential npm modules.

npx express --view=ejs
npm i -g express-generator
npm i
npm i express-flash express-session mongoose nodemon body-parser

Connect Node to MongoDB Database

For connecting the node app to MongoDB database, first make the database.js file then insert the provided code into the file.

var mongoose = require('mongoose')
mongoose.connect('mongodb://', {
  useNewUrlParser: true,
var conn = mongoose.connection
conn.on('connected', function () {
  console.log('Database connected')
conn.on('disconnected', function () {
  console.log('MongoDB disconnected ')
conn.on('error', console.error.bind(console))
module.exports = conn

Create Mongoose Schema

In your node app folder, create another folder and name it models/; After that, again create a new file and name it userModel.js.

Inside this file you have to place the given below code.

const mongoose = require("../database");
var userSchema = new mongoose.Schema({
            name: String,
            email: String
var userModel = mongoose.model('users', userSchema);
module.exports = mongoose.model("Users", userModel);

Build Routes in Node

Routes help you make the request to update or modify the data, therefore create the routes/ folder and also create users.js file then paste the given below code into the file.

var express = require('express');
var mongoose = require('mongoose');
var userModel = require('./models/userModel');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { page_title: 'Add User' });
});'/insert-user', function(req, res, next) {
    req.assert('name', 'Name is required').notEmpty()
    req.assert('email', 'Email is required').isEmail()
    var errors = req.validationErrors()
    if( !errors ) {
      var userDetails = new userModel({
      userDetails .save((err, doc) => {
            if (!err)
                req.flash('success', 'Data added.');
            else {
    else { 
        var errorInfo = ''
        errors.forEach(function(error) {
            errorInfo += error.msg + '<br>'
        req.flash('error', errorInfo)        
        res.render('/', { 
            page_title: 'Data added',
module.exports = router;

Build Form for Sending Data

Head over to views/ folder, in this folder you have open the index.ejs file.

In this file we will add the Bootstrap CDN and use it to form the HTML form that will help us to make the request to submit the data to MongoDB database.

<!DOCTYPE html>
<html lang="en">
    <title>Node Js Inser Document to MongoDB Example</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <div class="container mt-5">
      <% if (messages.success) { %>
      <p class="alert alert-success mt-3 mb-3"><%- messages.success %></p>
      <% } %>
      <form action="insert-user" method="POST">
        <div class="mb-4">
        <div class="mb-4">
        <button type="submit" class="btn btn-dark">Sumbit</button>

Configure Node Server

We now have to create the app.js file, in this file you will have to add the given below code hence open the file and add the provided code.

var createError = require('http-errors')
var path = require('path')
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser')
var flash = require('express-flash')
var session = require('express-session')
var express = require('express')
var userRoutes = require('./routes/users')
var app = express()
// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
app.use(express.urlencoded({ extended: false }))
app.use(express.static(path.join(__dirname, 'public')))
    secret: '123@abcd',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 },
app.use('/', userRoutes)
app.use(function (req, res, next) {
app.use(function (err, req, res, next) {
  res.locals.message = err.message
  res.locals.error ='env') === 'development' ? err : {}
  res.status(err.status || 500)
module.exports = app

Invoke Node Application

We have done the coding task, next invoke the given command and start the node server.


Open the app using the provided url on the browser to test the app.:

Node Js Insert Document in MongoDB Collection Tutorial


This guide explained how to create routes using express js easily and created a basic form using the noted Bootstrap UI framework. Successfully submitted the document or data to MongoDB’s collection through the Node js app.

Mongoose offers you an object modelling solution that you can align with MongoDB documents. Mongoose is the easiest and by far the best way to insert records in the MongoDB database.


A Full-stack developer with a passion to solve real world problems through functional programming.