Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在将csv转换为json字符串并进行解析后插入多个文档时,我在字段值中得到未定义的值。为什么?_Json_Node.js_Mongodb_Csv - Fatal编程技术网

在将csv转换为json字符串并进行解析后插入多个文档时,我在字段值中得到未定义的值。为什么?

在将csv转换为json字符串并进行解析后插入多个文档时,我在字段值中得到未定义的值。为什么?,json,node.js,mongodb,csv,Json,Node.js,Mongodb,Csv,基本上,我正在尝试为csv文件执行导入功能,csv文件将在插入mongodb之前转换为json。这是我的密码 //require the csvtojson converter class var Converter = require("csvtojson").Converter; // create a new converter object var converter = new Converter({}); var MongoClient = require('mongodb').M

基本上,我正在尝试为csv文件执行导入功能,csv文件将在插入mongodb之前转换为json。这是我的密码

//require the csvtojson converter class 
var Converter = require("csvtojson").Converter;
// create a new converter object
var converter = new Converter({});
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myproject';

// call the fromFile function which takes in the path to your 
// csv file as well as a callback function
converter.fromFile("./NTA-SAM-Inventory-List-Security-Management-
New_2017.csv",function(err,result){
// if an error has occured then handle it
if(err){
    console.log("An Error Has Occured");
    console.log(err);  
} 
// the result of the conversion
var jsonResult  = result;
console.log(jsonResult);
var jsobject= JSON.stringify(jsonResult);
var jsonobject= JSON.parse(jsobject);
var f = jsonobject.length;
console.log(f);
MongoClient.connect(url, function(err, db) {
        if(err) {
            console.log(err);
        }
        for(i = 0; i < f; i++){
    var insertDocument = function() {
    db.collection('documents').insertOne({
//'_id': Object.keys(obj).length,
        'indexNo' : jsonobject.indexNo,
        'samID': jsonobject.samID,
        'Type': jsonobject.Type,
        'InventoryStatus': jsonobject.InventoryStatus,
        'dateIn':jsonobject.dateIn,
        'Remarks':jsonobject.Remarks,
        'dateOut':jsonobject.dateOut,
        //'Remarks':jsonobject.remarks,
        'ntaSamRequestRef': jsonobject.ntaSamReqRef
        //'Created Date': "<b>" + day + "/" + month + "/" + year + "</b>"
    }, function(err, results) {
        if(err) throw err;
        console.log(results);

    });
    };
        insertDocument(db, function() {
            if(err)
                throw err;
            else{
                console.log('insert');
            }
            db.close();
        });
        }   
 });
        console.log("Inserted " + f + " document into the documents 
        collection.");
 });
//需要csvtojson转换器类
var转换器=需要(“csvtojson”)。转换器;
//创建新的转换器对象
var转换器=新转换器({});
var MongoClient=require('mongodb')。MongoClient;
var url='1〕mongodb://localhost:27017/myproject';
//调用fromFile函数,该函数接收到
//csv文件以及回调函数
converter.fromFile(“./NTA SAM库存清单安全管理-
新_2017.csv”,功能(错误、结果){
//如果发生错误,请处理它
如果(错误){
log(“发生错误”);
控制台日志(err);
} 
//转换的结果
var jsonResult=结果;
log(jsonResult);
var jsobject=JSON.stringify(jsonResult);
var jsonobject=JSON.parse(jsobject);
var f=jsonobject.length;
控制台日志(f);
连接(url,函数(err,db){
如果(错误){
控制台日志(err);
}
对于(i=0;i
到目前为止,我已经尝试过将一个包含1400条记录的随机文件转换成json字符串,然后再进行解析和插入。但不知何故,每当我插入时,我总是从字段中得到未定义的值,结果显示我各自的字段中有未定义的值

我的
jsonobject.indexNo
的哪一部分是错误的,即
jsonobject.field1value
jsonobject.field2value
等。解析后如何从json字符串中获取值?

我使用node.js运行它,并将mongodb作为数据库运行。我可以很好地转换这部分关于插入文档的内容。提前谢谢

db.collection('documents')。insertOne是一种异步方法,不能在这样的循环中运行它。解决方法是您可以用来处理它。建议使用

例如:

<代码> / /考虑JSOREST是一个数组 var jsonResult=结果; async.each(jsonResult, //这里,jsonobject是jsonResult数组的子对象 函数(jsonobject,回调){ db.集合(“文档”).insertOne({ //“_id”:Object.keys(obj).length, “indexNo”:jsonobject.indexNo, “samID”:jsonobject.samID, “类型”:jsonobject.Type, “InventoryStatus”:jsonobject.InventoryStatus, “dateIn”:jsonobject.dateIn, “备注”:jsonobject.备注, “dateOut”:jsonobject.dateOut, //“备注”:jsonobject.备注, “ntaSamRequestRef”:jsonobject.ntaSamReqRef //“创建日期”:“+day+”/“+month+”/“+year+”“ }); //异步调用完成,触发回调 回调(); }, //第三个参数是完成所有操作后要调用的函数 功能(err){ //所有任务现在都完成了 dosomethingoncalaredone(); } );
为什么要对原始结果进行字符串化,然后再次对其进行解析?原始结果将是一个json对象。调试时,是否在结果对象中获得预期的字段?@RedJandal我想在解析它之前先确保它是字符串这些行
var jsobject=JSON.stringify(jsonResult);var jsonobject=JSON.parse(jsobject)
应该完全没有必要,因为数据“已经”是JavaScript对象。这是“非”JSON。所以你不应该这样想。这里的主要问题是缺少适当的迭代器控制来完成回调。这是否意味着我应该在使用
async.each
之前将项放入数组中?我调用这些字段值的方式是否错误?可能应该是“至少”
async.eachLimit
否则堆栈上有很多并发调用。jsonResult是数组,对吗?只要它是一个数组,就可以使用它。用我的代码中的项目替换它。可能可以使用async.eachLimit来防止像@Neil Lunn said@digit这样的并发调用。很抱歉回复太晚。
f
重要吗?
项的作用是什么,我应该用什么替换它?
 // Consider jsonResult is an array
 var jsonResult  = result;

 async.each(jsonResult,
   // Here, jsonobject is a child object of jsonResult array
   function(jsonobject, callback){
     db.collection('documents').insertOne({
      //'_id': Object.keys(obj).length,
      'indexNo' : jsonobject.indexNo,
      'samID': jsonobject.samID,
      'Type': jsonobject.Type,
      'InventoryStatus': jsonobject.InventoryStatus,
      'dateIn':jsonobject.dateIn,
      'Remarks':jsonobject.Remarks,
      'dateOut':jsonobject.dateOut,
      //'Remarks':jsonobject.remarks,
      'ntaSamRequestRef': jsonobject.ntaSamReqRef
      //'Created Date': "<b>" + day + "/" + month + "/" + year + "</b>"
     });

     // Async call is done, trigger callback
     callback();
 },
 // 3rd param is the function to call when everything's done
 function(err){
   // All tasks are done now
   doSomethingOnceAllAreDone();
 }
);