2015-06-29 4 views
5

Sono nuovo con nodeJS e MongoDB. Ho questo codice:come inserire un documento .json nel server mongo di mongojs nel nodo

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; 
    }); 
}); 

nessun dato insered al MongoDB, e ho alcun errore. entrambi console.log (dati) stampano anche la stringa json.

risposta

6

Cercare di analizzare come JSON prima di inserirla nel documento

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; 
}); 
+0

Grazie !! Sta funzionando. – Avigayil