NodeJs Insert Data using Mongoose Save Function

NodeJs Insert Data using Mongoose Save Function

In this post you can learn how to Nodejs insert data using mongoose save function, mongoose save array of objects, mongoose insert document, how to insert mongoose documentation, How can we save mongoose.

Insert Document to MongoDB – to MongoDB, call save() method on document example.

In mongoose you can save data using save() function in node js. In this article we will create step by step to save data using mongoose save function.

Prerequisites of how to insert data in mongodb using node js

Step 1 : Install MongoDB

First you can install mongoDB environment  on your system. Install mongoDB from official website

step 2: Install required packages

Following package to you can easy to mongoose insert document in your project.

  • Express – popular web framework;
  • body-parser – body parser middleware, allows to access req.body property;
  • mongoose – Mongoose provides a straight-forward;
Read Also :  How do I read a JSON file in node JS

Following command to install express module in node js, install bosy-parser .

npm init -y
npm i express body-parser mongodb

Mongoose save example

Step 1 : Create the db.js file on your root directory in this file we will import mongoose module and connect with mongoDB database. In this file you include your model.


const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/testdb', { useNewUrlParser: true }, (err) => {
    if (!err) {
        console.log('MongoDB Connection Succeeded.')
    }else {
        console.log('Error in DB connection : ' + err)


Step 2 :  Create views/layout/layout.hbs file. If you have use handlebars(.hbs) extension, hbs require views folder.


<!DOCTYPE html>
    <title>Node.js express mongDB Insert</title>
    <link rel="stylesheet" href="" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
    <link rel="stylesheet" href="">
<body class="bg-info">
    <div class="row">
        <div class="col-md-6 offset-md-3" style="background-color: #fff;margin-top: 25px;padding:20px;">

Step 3 : Create the views/user/add.hbs file. In this file we have create basic html form for insert date in mongoose. In this form we have display validation error using node js.


        <div class="col-md-6 offset-md-3" style="background-color: #fff;margin-top: 25px;padding:20px;">
            <h1 class="text-center">{{titleName}}</h1>
            <form method="POST" action="/">
                <input type="text" name="username" placeholder="Enter username" class="form-control" />
                <div class="text-danger">
                <br />

                <input type="text" name="email" placeholder="Enter email" class="form-control" />
                <div class="text-danger">

                <br />
                <input type="password" name="password" placeholder="Enter password" class="form-control" />
                <div class="text-danger">
                <br />

                <input type="submit" value="Submit" class="btn btn-primary"/>          

Step 4 : Create the server.js file in root directory. This file is by default run your project. In this file we have include db.js connection file.

Read Also :  Update Data in MongoDB using Node js


const path = require("path");
const express = require("express");
const bodyparser = require("body-parser");
const exphbs = require("express-handlebars");
const userController = require("./controllers/userController");

var app = express();
    extended: true

app.set('views', path.join(__dirname, '/views/'));
app.engine('hbs', exphbs({ extname: 'hbs', defaultLayout: 'layout',
        runtimeOptions: {
          allowProtoPropertiesByDefault: true,
          allowProtoMethodsByDefault: true,
     layoutsDir: __dirname + '/views/layout' }));

app.set('view engine', 'hbs');
app.listen(3000, () => {
    console.log('Express server started at port : 3000');

app.use('/', userController);

Step 5 : Create models/users.js file. in this file we have create user schema code.

const mongoose = require("mongoose");
var uniqueValidator = require('mongoose-unique-validator');
var usersSchema = new mongoose.Schema({

    username : {
        type : String,
        required : 'Username is required.'

    email : {
        type : String,
        unique : true,
        required : 'Email is required.'

    password : {
        type : String,
        required : 'Password is required'

mongoose.model("Users", usersSchema);

Step 6 : Create controllers/userController.js file. In file we have create router, mongoose email validation, mongoose-unique-validator, mongoose error handling and Insert Document to MongoDB.

Read Also :  Fetch Data from Mongodb using Mongoose, Express.js, Node.js


const express = require("express");
var router = express.Router();
const mongoose = require('mongoose');
const Users = mongoose.model('Users');
mongoose.set('useFindAndModify', false);

router.get("/", (req,res) =>{
        titleName : 'Insert User'
});"/", (req,res) =>{

function insertRecord(req,res){

    var users = new Users();
    users.username = req.body.username; =;
    users.password = req.body.password;,doc) =>{
            if ( == 'ValidationError') {
                handleValidationError(err, req.body);
                res.render("user/add", {
                    titleName: "Insert User",
                    users: req.body

function handleValidationError(err, body) {

    for (field in err.errors) {
        switch (err.errors[field].path) {
            case 'username':
                body['usernameError'] = err.errors[field].message;
            case 'email':
                body['emailError'] = err.errors[field].message;
            case 'password':
                body['passwordError'] = err.errors[field].message;

module.exports = router;