Node.js Express : Insert JSON from POST request into MongoDB

Updated on 20th December 2016

This is a simple web app to retrieve JSON data from the body of a POST request and insert that data in a MongoDB collection.

In MongoDB, data records are stored as JSON documents which makes inserting JSON data a lot easier compared to other SQL databases. This app requires two modules

  • body-parse : This module is for parsing the JSON in the request body. The parsed result is made available on req.body property.
  • mongodb : This is the MongoDB driver for Node.js which allows your app to interact with the MongoDB database.

Both these modules can be installed with npm

npm install body-parser
npm install mongodb

Server-side

Here is the server side code for handling incoming JSON posts

File:server.js


//Receive data from JSON POST and insert into MongoDB

var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
var MongoClient = require('mongodb').MongoClient
var db;

//Establish Connection
MongoClient.connect('mongodb://localhost:27017/mydb', function (err, database) {
   if (err) 
   	throw err
   else
   {
	db = database;
	console.log('Connected to MongoDB');
	//Start app only after connection is ready
	app.listen(3000);
   }
 });

app.use(bodyParser.json())

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, '/myfile.html'));
});

app.post('/', function(req, res) {
   // Insert JSON straight into MongoDB
  db.collection('employees').insert(req.body, function (err, result) {
      if (err)
         res.send('Error');
      else
        res.send('Success');

  });
});

The MongoClient.connect() method establishes a connection to a MongoDB server on localhost and database mydb. If the database connection is successful, the Node server will start to listen for requests on port 3000. The app.listen() statement is inside the call back function for the MongoClient.connect() method, so the app starts listening only after a connection is established.

In this example the Node server will serve a HTML file myfile.html (see file contents below) when a user tries to access the server. This file contains the client-side code for sending JSON via AJAX.

File:myfile.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Node delivered HTML

</head>
<body>
   <div>
   	<h1>Send JSON to Node</h1>
        <button onClick="sendJSON()">Send</button>
        <p id ="result">
        </p>
   </div>
<script>
 var myData = [
	{
	    "name": "Bill",
	    "age": 20
	},
	{
	    "name": "Lisa",
	    "age": 40
	},
	{
	    "name": "Ant",
	    "age": 80
	}
    ]

function sendJSON(){

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       document.getElementById("result").innerHTML =
       this.responseText;
    }
 };
xmlhttp.open("POST", "http://localhost:3000");
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify(myData));

}

</script>
</body>
</html>

The use of bodyParser.json() ensures that the JSON is available in req.body. This can be directly inserted into a collection (sample collection employees). The req.body is passed to db.collection.insert() method along with a callback. AJAX response is set inside the callback function based on whether the insert was successful or not.


Post a comment

Got a question about this article? Ask our forum

Name

Your Comment

Email (We dont publish it)

Comments

;cl;x | September 7, 2017 4:23 PM |

cx,.fx