我有Mongo数据库,我想使用NodeJs API下载一个集合的所有注册表。我想下载像CSV或类似的东西。目前我有501426我的集合注册,所以当我调用.find()方法时,它返回此错误:
<--- Last few GCs --->
[15092:000001FE5E775B70] 95966 ms: Mark-sweep 1407.6 (1467.7) -> 1407.5
(1451.2) MB, 1408.9 / 0.0 ms last resort GC in old space requested
[15092:000001FE5E775B70] 97421 ms: Mark-sweep 1407.5 (1451.2) -> 1407.5
(1451.2) MB, 1454.2 / 0.0 ms last resort GC in old space requested
<--- JS stacktrace --->
==== JS stack trace =========================================
Security context: 000003F5F89A5EE1 <JSObject>
2: GetHash(aka GetHash) [native collection.js:1] [bytecode=000003F5F89D1721
offset=51](this=0000011364082311 <undefined>,o=000002F6E28FAE89 <JSFunction
wrapper (sfi = 000003167E337821)>)
4: set [native weak-collection.js:1] [bytecode=000003167E3380F9 offset=50]
(this=000001DB08591699 <JSWeakMap>,key=000002F6E28FAE89 <JSFunction wrapper
(sfi = 000003167E337821)>,value=00000021B54F67F9 <J...
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
我的代码是:
Collection.find({}).then(function(logs) {
res.charset = 'utf-8';
res.setHeader('Content-disposition', 'attachment; filename=' + 'filename.csv');
res.setHeader('content-type', 'text/csv');
csv
.write(logs, {
headers: true,
transform: function(row) {
return {
'Nivel': row.level,
'Metodo': row.method,
'IP': row.ip,
'URL': row.url,
'Status Code': row['status-code'],
'Usuario': row.user_email.email,
'Fecha': row.createdAt,
'Cuerpo': row.req_body,
'Consulta': row.req_query,
'Navegador': row['user-agent'],
'Datos Usuario': row.user_email,
'Aplicacion': row.referrer
};
}
})
.pipe(res);
})
此代码有效,但我想下载Collection的所有文档。抱歉我的英文。
由于
答案 0 :(得分:1)
不是一次性转换/解析内存,而是应该一个接一个地处理。为此我们首先需要Stream,我们可以将数据写入:
var csvStream = csv.createWriteStream({headers: true}),
csvStream.pipe(res); // directly pipe it to the user
然后我们可以按文档阅读集合文档,并将其传递给csv Transformer:
Collection.find({}).stream({
transform(row){
return {
'Nivel': row.level,
'Metodo': row.method,
'IP': row.ip,
'URL': row.url,
'Status Code': row['status-code'],
'Usuario': row.user_email.email,
'Fecha': row.createdAt,
'Cuerpo': row.req_body,
'Consulta': row.req_query,
'Navegador': row['user-agent'],
'Datos Usuario': row.user_email,
'Aplicacion': row.referrer
};
}
}).pipe(csvStream);