2016-01-31 26 views
0

我試圖使用babyParse將JSON對象轉換爲CSV並將生成的csv格式輸出到系統上的文件。無法使用PapaParse'unparse'將JSON轉換爲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,輸出的是什麼似乎是功能的頁面從寶寶解析模塊。

據我可以告訴在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; 

回答

2

的問題與allItems是貓鼬的文檔的集合,而不是普通的JavaScript對象。您可以使用.toObject()或者乾脆lean選項添加到您的查詢的對象轉換:

module.exports.downloadItemCsv = function(req, res){ 
    Item.find({}) 
     .sort({date:-1}) 
     .lean() 
     .exec(function(err, allItems){ 

     ... 
    }); 
}; 
+0

Cviejo您好,感謝上面的反饋;我會在今天晚些時候測試。你能告訴我爲什麼在將'allItems'記錄到控制檯時問題不明顯?這通常是我如何知道我現在在做什麼。很好理解爲什麼它沒有給出真實的圖景。 – ricky89

+1

當然。長話短說:'console.log'將輸出該特定對象具有的'toString()'的任何實現的結果。所以當你在一個貓鼬文檔上調用'toString()'時,它將從貓鼬方法和屬性中分離所有相關數據並返回它。你正在使用的這個庫,'babyparse' /'papaparse',正在分析這個對象,並且它不能說明哪些屬性是貓鼬相關或不相關的,這就是你所看到的意外輸出。 – cviejo

+0

加入'.lean()'就像魅力一樣工作。感謝你的目的背後的一塊/解釋。 – ricky89