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

▼魔方 西西 提交于 2019-12-19 19:49:16

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/31109764/how-to-insert-a-json-document-to-mongo-server-by-mongojs-in-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!