如何将 mongo 查询响应流式传输为 csv?

How to stream mongo query response as csv?

我有 collection,其中包含超过 500 万条记录。我需要查询数据并将其作为 csv 文件传递​​给客户端。最初当记录很少时,我们只是循环并将其写入文件并发送给客户端。但是现在随着记录不断增长,它会消耗内存,我们面临着问题。所以为了使用流我在下面尝试了,

   const cursor = Model.find(query)
        const transformer = (doc) => {
                return {
                    "Creator": doc.Entity_Creator,
                    "Action Date" : doc.E_Approve_Time,
                    "Remarks": doc.Entity_Comment
                }
            }
       
        let pat = path.join(__dirname, '../')
        var csvFilePath = '././downloads/' + ' Approved.csv'
        const filename = pat + csvFilePath
        res.setHeader('Content-disposition',`attachment;filename=${filename}`);
        res.writeHead(200,{ 'Content-Type': 'text/csv'})
        res.flushHeaders();

        var csvStream = fastCsv.format({headers: true}).transform(transformer)
        cursor.stream().pipe(csvStream).pipe(res)

但在下载后,我在单列中获得 Object Object 的文件。如何解决这个问题?

使用这个

        const transformer = (doc) => {
          return {
            Creator: doc.Entity_Creator,
            "Action Date": doc.E_Approve_Time,
            Remarks: doc.Entity_Comment,
          };
        };
        
        let pat = path.join(__dirname, "../");
        var csvFilePath = "././downloads/" + " Approved.csv";
        const filename = pat + csvFilePath;
        res.setHeader("Content-disposition", `attachment;filename=${filename}`);
        res.writeHead(200, { "Content-Type": "text/csv" });
        res.flushHeaders();
        
        var csvStream = fastCsv.format({ headers: true }).transform(transformer);
        
        csvStream.pipe(process.stdout).on("end", () => process.exit());
        
        Model.find(query).exec(function (err, cursor) {
                if (err) {
                    console.log(err);
                    console.log('error returned');
                    return false;
                }
               if (!data) {
                    console.log('Authentication Failed');
                    return false;
                }
        cursor.forEach((e) => {
          csvStream.write({
            Creator: e.Entity_Creator,
            "Action Date": e.E_Approve_Time,
            Remarks: e.Entity_Comment,
          });
        });
       }) 
        csvStream.end();