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

1

6

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.

Ferrel answered 29/6, 2015 at 7:11 Comment(0)
T
7

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;
    });
});
Toxinantitoxin answered 29/6, 2015 at 7:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.