我正在尝试使用babyParse将JSON对象转换为CSV并将生成的csv格式输出到系统上的文件。
module.exports.downloadItemCsv = function(req, res){
Item.find({})
.sort({date:-1})
.exec(function(err, allItems){
if(err){
res.error(err)
} else{
var configuration = {
quotes: false,
delimiter: ",",
newline: "\r\n"
};
console.log(allItems);
console.log("Adding items to object.");
var csv = baby.unparse(allItems, configuration);
var targetPath = path.join(__dirname,"../../uploads/" + "newFile01");
fs.writeFile(targetPath, csv, function(err){
if(err){
console.log("Write complete!")
}
});
console.log("The file was saved!");
res.json({status: 200})
}
})
};
console.log(allItems);
输出正确的JSON对象,但是当我为csv变量执行console.log时,输出似乎是来自婴儿Parse模块的函数页面。
据我在PapaParse文档中可以看出,我只需要在行var csv = baby.unparse(allItems, configuration);
中传递JSON对象。
一旦我在变量" csv"中有非粗略数据,我应该能够将csv写入文件。有谁知道为什么JSON对象没有被解析为csv对象?
以下是allItems中的数据:
[ { __v: 0,
itemId: 2507,
item: 'TEST',
description: 'TEST',
brand: 'TEST',
category: 'TEST',
subcategory: 'TEST',
size: '10',
gender: 'F',
costPrice: 10,
salePrice: 10,
saleDate: '2016-01-31',
purchaseDate: '2016-01-31',
_id: 56ae7972049ce640150453b7 } ]
下面是填充到变量" csv"中的结果的施加。完整的结果是放在下面。
$__,isNew,errors,_doc,$__original_save,save,_pres,_posts,db,discriminators,__v,id,_id,purchaseDate,saleDate,salePrice,costPrice,gender,size,subcategory,category,brand,description,item,itemId,schema,collection,$__handleSave,$__save,$__delta,$__version,increment,$__where,remove,model,on,once,emit,listeners,removeListener,setMaxListeners,removeAllListeners,addListener,$__buildDoc,init,$__storeShard,hook,pre,post,removePre,removePost,_lazySetupHooks,update,set,$__shouldModify,$__set,getValue,setValue,get,$__path,markModified,modifiedPaths,isModified,$isDefault,isDirectModified,isInit,isSelected,validate,$__validate,validateSync,invalidate,$markValid,$isValid,$__reset,$__dirty,$__setSchema,$__getArrayPathsToValidate,$__getAllSubdocs,$__registerHooksFromSchema,$__handleReject,$toObject,toObject,toJSON,inspect,toString,equals,populate,execPopulate,populated,depopulate,$__fullPath
[object Object],false,,[object Object],"function () {
var self = this
, hookArgs // arguments eventually passed to the hook - are mutable
, lastArg = arguments[arguments.length-1]
, pres = this._pres[name]
, posts = this._posts[name]
, _total = pres.length
, _current = -1
, _asyncsLeft = proto[name].numAsyncPres
, _asyncsDone = function(err) {
if (err) {
return handleError(err);
}
--_asyncsLeft || _done.apply(self, hookArgs);
}
, handleError = function(err) {
if ('function' == typeof lastArg)
return lastArg(err);
if (errorCb) return errorCb.call(self, err);
throw err;
答案 0 :(得分:2)
问题与allItems
是Mongoose Documents的集合有关,而不是普通的javascript对象。您可以使用.toObject()转换这些对象,或者只需在查询中添加lean选项:
module.exports.downloadItemCsv = function(req, res){
Item.find({})
.sort({date:-1})
.lean()
.exec(function(err, allItems){
...
});
};