无法使用 PapaParse 'unparse' 将 JSON 转换为 CSV

Unable to use PapaParse 'unparse' to convert JSON to CSV

我正在尝试使用 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;

问题与 allItems 是 Mongoose 文档的集合有关,而不是普通的 javascript 对象。您可以使用 .toObject() or simply add the lean 选项将这些对象转换为您的查询:

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

        ...
    });
};