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 https://www.mongodb.com.

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 :  Crud Operation using Node.js Express MongoDB

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.

db.js

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)
    }
});

require('./models/users');

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

views/layout/layout.hbs

<!DOCTYPE html>
<html>
<head>
    <title>Node.js express mongDB Insert</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
        crossorigin="anonymous">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body class="bg-info">
    <div class="row">
        <div class="col-md-6 offset-md-3" style="background-color: #fff;margin-top: 25px;padding:20px;">
            {{{body}}}
        </div>
    </div>
</body>
</html>

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.

Read Also :  Update Data in MongoDB using Node js

views/user/add.hbs

        <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">
                        {{users.usernameError}}</div>
                <br />

                <input type="text" name="email" placeholder="Enter email" class="form-control" />
                <div class="text-danger">
                        {{users.emailError}}</div>

                <br />
                <input type="password" name="password" placeholder="Enter password" class="form-control" />
                <div class="text-danger">
                        {{users.passwordError}}</div>
                <br />

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

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.

server.js

require("./db");
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();
app.use(bodyparser.urlencoded({
    extended: true
}));

app.use(bodyparser.json());
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);
usersSchema.plugin(uniqueValidator);

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

controllers/userController.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) =>{
    res.render("user/add",{
        titleName : 'Insert User'
    });
});

router.post("/", (req,res) =>{
        insertRecord(req,res);
});

function insertRecord(req,res){

    var users = new Users();
    users.username = req.body.username;
    users.email = req.body.email;
    users.password = req.body.password;

    users.save((err,doc) =>{
        if(!err)
        res.redirect("users/list");
        else{
            if (err.name == '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;
                break;
            case 'email':
                body['emailError'] = err.errors[field].message;
                break;
            case 'password':
                body['passwordError'] = err.errors[field].message;
                    break;
            default:
                break;
        }
    }
}

module.exports = router;