在我的node.js应用程序中,我从
mongodb服务器检索值,并希望将它们转换为CSV文件.可以从数据库轻松访问父元素并显示在CSV文件中但子元素不显示且无法访问..
JSON结构:
"name" : "fhj","age" : "23","gender" : "female","sec" : "b","username" : "9886666","language" : "hindi","method" : "method2","timeSlot" : { "id" : 2,"fromTime" : 12,"toTime" : 15 }
mycode的:
db.users.find(function(err,values){ if(err||!values.length) console.log("ERROR !!!!"); else { var i=1; str='['; values.forEach(function(user){ if(i==values.length) str=str+'{ "name" : "' + user.username + '","age" : "'+ user.age +'","gender":"'+user.gender+'","sec":"'+user.sec+'","username":"'+user.username+'","language":"'+user.language+'","method":"'+user.method+'","Timeslot":"'+user.timeslot+'"}'; else{ str = str + '{ "name" : "' + user.username + '","Timeslot":"'+user.timeslot+'"},' +'\n'; i++; } }); str = str.trim(); str = str + ']'; var obj=JSON.parse(str); json2csv({data: obj,fields: ['name','age','gender','sec','username','language','method','Timeslot']},function(err,csv) { if (err) console.log(err); fs.writeFile('./files/user.csv',csv,function(err) { if (err) throw err; console.log('File saved'); }); }); } });
解决方法
可以在
following thread(访问嵌套数据结构)的答案中找到访问嵌套元素的简单方法.
A nested data structure is an array or object which refers to other arrays or objects,i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.
As we can see timeSlot is an object,hence we can access its properties using dot notation. The items property is accessed as follows:
timeSlot.id
Alternatively,we Could have used bracket notation for any of the properties,especially if the name contained characters that would have made it invalid for dot notation usage:
var item_name = timeSlot['id'];
获得所需的所有数据后,CSV文件的创建应该非常简单:)