嗨在我的Sailsjs应用程序中,有一个批量上传功能,管理员可以上传csv文件。我正在使用csv-parse来解析csv内容。
现在我想将数据插入Mongo DB,其中每行都有车辆信息和测试信息。这两个模型有一对多的关系。我无法弄清楚如何将它们插入数据库。下面是我插入车辆的代码。
下面是我想创建VehicleTest模型的代码示例一旦创建了车辆模型,但我无法访问车辆以获取vechileTest模型的信息
车辆型号
attributes: {
vehicleTested :{
modal :'Vehicle',
required:true
},
VechileTest模型
var parse = require('csv-parse');
var fs = require("fs")
var createdVehicle =[];
var stream = files[0].fd;
fs.readFile(stream, 'utf8', function (err, data) {
// Print the contents of the file as a string here
// and do whatever other string processing you want
parse(data, {columns: true,delimiter:'|'}, function(err, output){
if(output.length>0)
{
for (var i = 0, len = output.length; i < len; i++) {
var vehicle_TestInfo = output[i];
//console.log(vehicle_TestInfo);
//
Vehicle.create({make : vehicle_TestInfo.make,model:vehicle_TestInfo.model,year:vehicle_TestInfo.year ,engineFuel:vehicle_TestInfo.engineFuel,obdZone:vehicle_TestInfo.obdZone,generation:vehicle_TestInfo.generation,protocol:vehicle_TestInfo.protocol,onStar:vehicle_TestInfo.onStar}).exec(function(err,vehCreated){
console.log(vehCreated);
//VehicleTest.Create({vehicleTested:vehCreated._id,overAllComp:vehicle_TestInfo.overAllComp,deviceGeneration:vehicle_TestInfo.deviceGeneration}).exec(function(err,testCreated){
//
// console.log(testCreated);
//
//})
});
}
}
函数的代码行下面读取文件并解析它
;
答案 0 :(得分:0)
这是我实施的方式
for (var i = 0, len = output.length; i < len; i++) {
var vehicle_TestInfo = output[i];
//console.log(vehicle_TestInfo);
//
Vehicle.create({make : vehicle_TestInfo.make,model:vehicle_TestInfo.model,year:vehicle_TestInfo.year ,trim:vehicle_TestInfo.trim ,engineFuel:vehicle_TestInfo.engineFuel,obdZone:vehicle_TestInfo.obdZone,generation:vehicle_TestInfo.generation,protocol:vehicle_TestInfo.protocol,onStar:vehicle_TestInfo.onStar,
tests : {deviceGeneration:vehicle_TestInfo.deviceGeneration,overAllComp:vehicle_TestInfo.overAllComp,isTested:vehicle_TestInfo.isTested,testingInferred:vehicle_TestInfo.testingInferred,vinRead:vehicle_TestInfo.vinRead,
odoRead:vehicle_TestInfo.odoRead,pidRead:vehicle_TestInfo.pidRead,doorLocked:vehicle_TestInfo.doorLocked,SeatBelt:vehicle_TestInfo.seatBelt,fuelLevel:vehicle_TestInfo.fuelLevel,issueType:vehicle_TestInfo.issueType,degreeOfERGIntr:vehicle_TestInfo.degreeOfERGIntr,dataLoggerModel:vehicle_TestInfo.dataLoggerModel,
numberOfVehicle:vehicle_TestInfo.numberOfVehicle,remarks:vehicle_TestInfo.remarks}}).exec(function(err,vehCreated){
if(err && err.originalError && err.originalError.code===50)
{
Vehicle.update({id:vehCreated.id})
}
/// console.log(vehCreated);
// vehCreated.tests.add({})
createdVehicle.push(vehCreated);
});