/ / comment insérer un document .json sur un serveur mongo par mongojs dans node - json, node.js, fs, mongojs

comment insérer un document .json sur un serveur mongo par mongojs dans node - json, node.js, fs, mongojs

Je suis nouveau avec nodeJS et MongoDB. J'ai ce 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;
});
});

aucune donnée insérée à la mongodb, et je n'ai aucune erreur. les deux console.log (data) impriment également la chaîne json.

Réponses:

6 pour la réponse № 1

Essayez de l'analyser au format JSON avant de l'insérer dans le 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;
});