NodeJS/Express – POST/GET data to/from MongoDB using Mongoose – Ajax JQuery + Bootstrap form example

In the tutorial, we show you how to POST/GET form data to/from MongoDB in NodeJS/Express application using Mongoose with Ajax JQuery & Bootstrap view.

Related posts:
Crud RestAPIs with NodeJS/Express, MongoDB using Mongoose
Integrate NodeJS/Express – JQuery Ajax POST/GET – Bootstrap view

Goal

Technologies
– NodeJS/Express
– Mongoose
– MongoDB
– JQuery Ajax
– Bootstrap

We create a NodeJS/Express project as below structure:

/NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB
	/app
		/config
			mongodb.config.js
		/controllers
			user.controller.js
		/models
			user.model.js
		/routes
			user.route.js
	/node_modules
	/resources
		/static
			/js	
				getrequest.js
				postrequest.js
	/views
		404.html
		index.html
	app.js
	package.json

Run above project then makes POST/GET requests, results:

-> Bootstrap view:

NodeJS-Express-Post-Get-data-to-MongoDB-using-Moongoose-Ajax-JQuery-Bootstrap-view-results

-> MongoDB’s collections:

NodeJS-Express-Post-Get-data-to-MongoDB-using-Moongoose-Ajax-JQuery-Bootstrap-view-MongoDB-all-records

Practice

Setting up NodeJS/Express project

Create a folder: ‘NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB’:

mkdir NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB
cd NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB

Then init NodeJS project, see prompts:

NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install ` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (nodejs-express-ajax-jquery-bootstrap-mongodb)
version: (1.0.0)
description: building a NodeJS/Express web-app to POST/GET data from MongDB via Mongoose - Ajax JQuery + Bootstrap view
entry point: (index.js) server.js
test command:
git repository:
keywords: NodeJS, Express, MongoDB, Mongoose, JQuery, Bootstrap
author: ozenero.com
license: (ISC)
About to write to C:\Users\pc\Desktop\nodejs\NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB\package.json:

{
  "name": "nodejs-express-ajax-jquery-bootstrap-mongodb",
  "version": "1.0.0",
  "description": "building a NodeJS/Express web-app to POST/GET data from MongDB via Mongoose - Ajax JQuery + Bootstrap view",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "NodeJS",
    "Express",
    "MongoDB",
    "Mongoose",
    "JQuery",
    "Bootstrap"
  ],
  "author": "ozenero.com",
  "license": "ISC"
}


Is this ok? (yes) yes

-> Install Express, Body-Parser, Mongoose:

npm install express body-parser mongoose --save

-> see package.json file:

{
  "name": "nodejs-express-ajax-jquery-bootstrap-mongodb",
  "version": "1.0.0",
  "description": "building a NodeJS/Express web-app to POST/GET data from MongDB via Mongoose - Ajax JQuery + Bootstrap view",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "NodeJS",
    "Express",
    "MongoDB",
    "Mongoose",
    "JQuery",
    "Bootstrap"
  ],
  "author": "ozenero.com",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.3",
    "mongoose": "^5.0.17"
  }
}
Frontend
Create Bootstrap views

./view/index.html file:




  JQuery Ajax - Bootstrap - NodeJS/Express - MySQL
  
  
  
  
  
  
  

 
 

NodeJS/Express Post/Get Ajax


./views/404.html file:




  Bootstrap Example
  
  
  
  
  


  

404 Error!

PAGE NOT FOUND

Implement Ajax JQuery to Post/Get data

– For JQuery Ajax POST request, we implement a ./resources/static/js/postrequest.js file:

$( document ).ready(function() {
	
	// SUBMIT FORM
    $("#userForm").submit(function(event) {
		// Prevent the form from submitting via the browser.
		event.preventDefault();
		ajaxPost();
	});
    
    
    function ajaxPost(){
    	
    	// PREPARE FORM DATA
    	var formData = {
    		firstname : $("#firstname").val(),
    		lastname :  $("#lastname").val()
    	}
    	
    	// DO POST
    	$.ajax({
			type : "POST",
			contentType : "application/json",
			url : window.location + "api/users/save",
			data : JSON.stringify(formData),
			dataType : 'json',
			success : function(user) {
				$("#postResultDiv").html("

" + "Post Successfully!
" + "--> " + user.firstname + " " + user.lastname + "

"); }, error : function(e) { alert("Error!") console.log("ERROR: ", e); } }); // Reset FormData after Posting resetData(); } function resetData(){ $("#firstname").val(""); $("#lastname").val(""); } })

– For JQuery Ajax Get request, we implement a ./resources/static/js/getrequest.js file:

$( document ).ready(function() {
	
	// GET REQUEST
	$("#allUsers").click(function(event){
		event.preventDefault();
		ajaxGet();
	});
	
	// DO GET
	function ajaxGet(){
		$.ajax({
			type : "GET",
			url : "/api/users/all",
			success: function(result){
				$('#getResultDiv ul').empty();
				$.each(result, function(i, user){
					$('#getResultDiv .list-group').append(user.firstname + " " + user.lastname + "
") }); console.log("Success: ", result); }, error : function(e) { $("#getResultDiv").html("Error"); console.log("ERROR: ", e); } }); } })
Backend
Create Mongoose model

./app/models/user.model.js file:

const mongoose = require('mongoose');
 
const UserSchema = mongoose.Schema({
    firstname: String,
    lastname: String
});
 
module.exports = mongoose.model('User', UserSchema);
Configure MongoDB connection

./app/config/mongodb.config.js file:

module.exports = {
    url: 'mongodb://localhost:27017/nodejs-demo'
}
Create Express Routes

./app/routes/user.route.js file:

module.exports = function(app) {
 
	var express = require("express");
	var router = express.Router();
	
    const users = require('../controllers/user.controller.js');
	
	var path = __basedir + '/views/';
	
	router.use(function (req,res,next) {
		console.log("/" + req.method);
		next();
	});
	
	app.get('/', (req,res) => {
		res.sendFile(path + "index.html");
	});
 
    // Save a User to MongoDB
    app.post('/api/users/save', users.save);
 
    // Retrieve all Users
    app.get('/api/users/all', users.findAll);
	
	app.use("/",router);
 
	app.use("*", (req,res) => {
		res.sendFile(path + "404.html");
	});
}
Implement Controllers

./app/controllers/user.controller.js file:

const User = require('../models/user.model.js');
 
// Save FormData - User to MongoDB
exports.save = (req, res) => {
	console.log('Post a User: ' + JSON.stringify(req.body));
	
    // Create a Customer
    const user = new User({
        firstname: req.body.firstname,
		lastname: req.body.lastname
    });
 
    // Save a Customer in the MongoDB
    user.save()
    .then(data => {
        res.send(data);
    }).catch(err => {
        res.status(500).send({
            message: err.message
        });
    });
};
 
// Fetch all Users
exports.findAll = (req, res) =>  {
	console.log("Fetch all Users");
	
    User.find()
    .then(users => {
        res.send(users);
    }).catch(err => {
        res.status(500).send({
            message: err.message
        });
    });
};
Implement App.js

./app.js file:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
 
app.use(express.static('resources'));
 
global.__basedir = __dirname;

// Configuring the database
const dbConfig = require('./app/config/mongodb.config.js');
const mongoose = require('mongoose');
 
mongoose.Promise = global.Promise;
 
// Connecting to the database
mongoose.connect(dbConfig.url)
.then(() => {
    console.log("Successfully connected to MongoDB.");    
}).catch(err => {
    console.log('Could not connect to MongoDB.');
    process.exit();
});
 
require('./app/routes/user.route.js')(app);
 
// Create a Server
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("App listening at http://%s:%s", host, port)
 
})
Run & Check results

Start NodeJS server:

-> Logs:

NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB>node app.js
App listening at http://:::8081
Successfully connected to MongoDB.
/GET
Post a User: {"firstname":"Jack","lastname":"Davis"}
Post a User: {"firstname":"Mary","lastname":"Taylor"}
Post a User: {"firstname":"Peter","lastname":"Thomas"}
Post a User: {"firstname":"Amos","lastname":"Nelson"}
Post a User: {"firstname":"Craig","lastname":"White"}
Post a User: {"firstname":"Laura","lastname":"Lewis"}
Post a User: {"firstname":"Steven","lastname":"Harris"}
Post a User: {"firstname":"Paul","lastname":"Moore"}
Post a User: {"firstname":"Mary","lastname":"Cook"}
Fetch all Users

-> POST/GET requests:

NodeJS-Express-Post-Get-data-to-MongoDB-using-Moongoose-Ajax-JQuery-Bootstrap-view-requests

Sourcecode

To run below sourcecode, follow below guides:

step 0: download & extract zip file -> we have a folder 'NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB'
step 1: cd NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB
step 2: npm install express body-parser mongoose --save
step 3: node app.js  

Sourcecode:

NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB

4 thoughts on “NodeJS/Express – POST/GET data to/from MongoDB using Mongoose – Ajax JQuery + Bootstrap form example”

Leave a Reply

Your email address will not be published. Required fields are marked *