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

1. Install Mongoose

First, you need to install Mongoose in your project. You can do this by running the following command in your terminal:

npm install mongoose

2. Connect to MongoDB

Once you have installed Mongoose, you need to connect to your MongoDB database. You can do this by creating a Mongoose connection object and passing it the connection string for your MongoDB database.

const mongoose = require(‘mongoose’);

mongoose.connect(‘mongodb://localhost/my_database’, {
useNewUrlParser: true,
useUnifiedTopology: true
});

3. Create a Mongoose Model

Next, you need to create a Mongoose model for the collection you want to insert data into. A Mongoose model is a constructor that creates documents.

const User = mongoose.model(‘User’, {
name: String,
age: Number
});

4. Create a Document

Once you have created a Mongoose model, you can create a document using the model’s constructor.

const user = new User({
name: ‘John Doe’,
age: 25
});

5. Save the Document

Finally, you can save the document to your MongoDB database by calling the save() method on the document.

user.save(function(err) {
if (err) return handleError(err);
// saved!
});

Save/insert data from the form into mongoDB database in node js express app; In this tutorial, you will learn how to insert/save/store data from HTML form into mongoDB database using mongoose in node js express app.

Mongoose is the best solution to insert data into MongoDB.Because It is very easy & fast. So, In this tutorial, you will find simeple and easy example to insert form data in Node.js Express.

This tutorial will create a simple form using bootstrap 4 library and then create route in app.js file for inserting data into the MongoDB database using mongoose in node js express app.

How to Insert Data into MongoDB Using Mongoose in Node.js Express

Follow the following steps to insert data into MongoDB using mongoose and node. js:

  • Step 1 – Create Node Express js App
  • Step 2 – Install express flash ejs body-parser mongoose dependencies
  • Step 3 – Connect App to MongoDB
  • Step 4 – Create Model
  • Step 5 – Create Routes
  • Step 6 – Create HTML Markup Form
  • Step 7 – Import Modules in App.js
  • Step 8 – Start App Server

Step 1 – Create Node Express js App

Execute the following command on terminal to create node js app:

mkdir my-app
cd my-app
npm init -y

Step 2 – Install express flash ejs body-parser mongoose Modules

Execute the following command on the terminal to express flash ejs body-parser mysql dependencies :

npm install -g express-generator
npx express --view=ejs

npm install

npm install express-flash --save
npm install express-session --save
npm install body-parser --save
npm install express-validator cors --save
npm install mongoose

body-parser – Node.js request body parsing middleware which parses the incoming request body before your handlers, and make it available under req.body property. In other words, it simplifies the incoming request.

Express-Flash – Flash Messages for your Express Application. Flash is an extension of connect-flash with the ability to define a flash message and render it without redirecting the request.

Express-Session– Express-session – an HTTP server-side framework used to create and manage a session middleware.

Express-EJS– EJS is a simple templating language which is used to generate HTML markup with plain JavaScript. It also helps to embed JavaScript to HTML pages

Mongoose – Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks.

Step 3 – Connect App to MongoDB

Create database.js file into your app root directory and add the following code into it to connect your app to the mongodb database:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true});
var conn = mongoose.connection;
conn.on('connected', function() {
    console.log('database is connected successfully');
});
conn.on('disconnected',function(){
    console.log('database is disconnected successfully');
})
conn.on('error', console.error.bind(console, 'connection error:'));
module.exports = conn;

Step 4 – Create Model

Create Models directory and inside this directory create userModel.js file; Then add following code into it:

const mongoose = require("../database");

// create an schema
var userSchema = new mongoose.Schema({
            name: String,
            email:String
        });

var userModel=mongoose.model('users',userSchema);

module.exports = mongoose.model("Users", userModel);

Step 5 – Create Routes

Create routes; so visit routes directory and open users.js route file; Then add the following routes into it:

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


/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'add user' });
});

router.post('/add-user', function(req, res, next) {
    
    req.assert('name', 'Name is required').notEmpty()           //Validate name
    req.assert('email', 'A valid email is required').isEmail()  //Validate email
 
    var errors = req.validationErrors()
    
    if( !errors ) {   //No errors were found.  Passed Validation!
        
    
      var userDetails = new userModel({
        name: req.body.name,
        email: req.body.email,
      });
      
      userDetails .save((err, doc) => {
            if (!err)
                req.flash('success', 'User added successfully!');
                res.redirect('/');
            else
                console.log('Error during record insertion : ' + err);
      });
  
    }
    else {   //Display errors to user
        var error_msg = ''
        errors.forEach(function(error) {
            error_msg += error.msg + '<br>'
        })                
        req.flash('error', error_msg)        
        
        res.render('/', { 
            title: 'Add New User',
            name: req.body.name,
            email: req.body.email
        })
    }
});

module.exports = router;

Step 6 – Create HTML Markup Form

Create html form for inserting data into database; So visit views directory and create index.ejs file inside it. Then add the following code into it:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Node.js Express Save Data from Html Form to Mongodb Database - Tutsmake.com</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  </head>
  <body>
    <div class="container mt-4">
      <div class="card">
        <div class="card-body">
          <% if (messages.success) { %>
              <p class="alert alert-success m2-4 mb-2"><%- messages.success %></p>
          <% } %>  

          <h2>Node.js Express Save Data from Html Form to Mongodb Database - Tutsmake.com</h2>

          <form action="add-user" method="POST">
            <div class="form-group">
              <label for="firstName">Name</label>
              <input type="text" class="form-control col-lg-9" id="name" aria-describedby="emailHelp" placeholder="Enter first name" name="name">
            </div>
            <div class="form-group">
              <label for="exampleInputEmail1">Email address</label>
              <input type="email" class="form-control col-lg-9" id="exampleInputEmail1" aria-describedby="emailHelp" name="email" placeholder="Enter email">
            </div>        
            <button type="submit" class="btn btn-primary">Submit</button>
          </form>
    </div>
  </div>
  </body>
</html>

Step 7 – Import Modules in App.js

Import express flash session body-parser mongoose dependencies in app.js; as shown below:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var flash = require('express-flash');
var session = require('express-session');
var usersRouter = require('./routes/users');


var app = express();


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({ 
    secret: '123456catr',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 }
}))

app.use(flash());
app.use('/', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

Step 8 – Start App Server

You can use the following command to start node js app server:

//run the below command

npm start

after run this command open your browser and hit 

http://127.0.0.1:3000/

Conclusion

Save/insert data from form into mongoDB database in node js express app; In this tutorial, you have learned how to insert/save/store data from HTML form into mongoDB database using node js express app.

Recommended Node JS Tutorials

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?