NodeJS: saving JSON to MongoDB

I am trying to get JSON from an API and store it into a MongoDB database.
Obviously, it doesn’t work. My app seems to hang around the point where I try to save the data to the database. Please advise what to do.

Here’s my code:

var express = require('express');
var router = express.Router();
var http = require('http');
var mongo = require('mongoskin');
var db = mongo.db("mongodb://localhost:27017/zak", {native_parser : true});

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

var site = '';

function getData(cb) {

    http.get(site, function(res) {
        // explicitly treat incoming data as utf8 (avoids issues with multi-byte chars)

        // incrementally capture the incoming response body
        var body = '';
        res.on('data', function(d) {
            body += d;

        // do whatever we want with the response once it's done
        res.on('end', function() {
            try {
                var parsed = JSON.parse(body);
            } catch (err) {
                console.error('Unable to parse response as JSON', err);
                return cb(err);

            // pass the relevant data back to the callback
    }).on('error', function(err) {
        // handle errors with the request itself
        console.error('Error with the request:', err.message);


function writeData (data, allGood){     

// couple of visual checks if all looking good before writing to db
console.log(typeof data);

db.collection('zakazky').save(data, function(error, record){
if (error) throw error;
console.log("data saved");


function allGood(){console.log('all done');}


// ---------------------
module.exports = router;

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You are calling the save() instead of insert(). Change this part and it will work:

// this should call insert, not save
db.collection('zakazky').insert(data, function(error, record){
    if (error) throw error;
    console.log("data saved");

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply