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

by Remy Pereira 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


Here is the server side code for handling incoming JSON posts


//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
	db = database;
	console.log('Connected to MongoDB');
	//Start app only after connection is ready


app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, '/myfile.html'));
});'/', function(req, res) {
   // Insert JSON straight into MongoDB
  db.collection('employees').insert(req.body, function (err, result) {
      if (err)


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.


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

   	<h1>Send JSON to Node</h1>
        <button onClick="sendJSON()">Send</button>
        <p id ="result">
 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 =
 };"POST", "http://localhost:3000");
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");



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.

Also Read

Post a comment


Prerna | May 8, 2020 8:47 AM |

TypeError: db.collection is not a function

Ephraim | May 10, 2020 12:09 PM |

That's a bug with some version of mongodb library.. Try db().collection('employees') instead.

varsha rani n | March 5, 2019 6:21 AM |

Hi, i ran the above code but i'm not getting output. Please help me with this..... I need to read Json data from .json file and save into mongodb.