遥测表中的数据量巨大。因此,我收到“JavaScript 堆内存不足”错误。 我该如何克服这个错误?
const aloUrl = `mongodb://${userName}:${pwd}@${host}:${port}/${dbName}`;
MongoClient.connect(aloUrl, function(err, client) {
if (err) {
return console.log('ERROR:: ', err);
}
console.log("INFO:: OK");
const db = client.db(dbName);
var arr = db.collection('endpoint').find({provider:"KMR"}).map(e => e._id).toArray((err, result) => {
if (err){
console.log("ERROR", err)
}
var son = db.collection('telemetry').find({endpoint: {$in: result}}).toArray().then(arr =>{
console.log("Let's start to party")
for (let i = 0; i < 10; i++) {
console.log("\t" + arr[i]._id)
}
}).catch(e => {
console.log(`ERROR::${e}`)
})
})
});
最佳答案
来自 mongodb 文档,
The toArray() method returns an array that contains all the documents from a cursor. The method iterates completely the cursor, loading all the documents into RAM and exhausting the cursor.
因此,您应该使用 next
或 forEach
(或其他不会立即加载所有内容的方法,而不是调用 toArray
RAM),逐个迭代元素。
例如,要一一打印遥测集合中的所有文档,您可以这样做,
db.collection('telemetry')
.find({
endpoint: {
$in: result
}
})
.forEach((document) => {
console.log(document)
});
关于javascript - MongoDB&JavaScript 堆内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48095401/