Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to insert a .json document to mongo server by mongojs in node

I'm new with nodeJS and MongoDB. I have this code:

var fs = require('fs');
var mongojs = require('mongojs');
var db = mongojs('monitor', ["configurations"]);

fs.readFile('json/object1.json', 'utf8', function (err, data) {
    if (err) throw err;
    console.log(data);

    db.configurations.insert(data, function(err, doc) {
        console.log(data);
    if(err) throw err;
  });
});

no data insered to the mongodb, and I've got no error. the both console.log(data) print the json string as well.

like image 297
Avigayil Avatar asked Jun 29 '15 07:06

Avigayil


1 Answers

Try to parse it as JSON before inserting it into the document

fs.readFile('json/object1.json', 'utf8', function (err, data) {
    if (err) throw err;
    console.log(data);
    var json = JSON.parse(data);

    db.configurations.insert(json, function(err, doc) {
        console.log(data);
        if(err) throw err;
    });
});
like image 52
Bidhan Avatar answered Oct 20 '22 12:10

Bidhan