【发布时间】:2018-07-10 19:27:39
【问题描述】:
我想循环抛出我的 MongoDB 的特定集合中的所有文档。但是,由于光标超时,我所做的每一次尝试都失败了。这是我的代码
let MongoClient = require('mongodb').MongoClient;
const url = "my connection URI"
let options = { socketTimeoutMS: 120000, connectTimeoutMS: 120000, keepAlive: 100, poolSize: 5 }
MongoClient.connect(url, options,
function(err, db) {
if (err) throw err
let dbo = db.db("notes")
let collection = dbo.collection("stats-network-consumption")
let stream = collection.find({}, { timeout: false }).stream()
stream.on("data", function(item) {
printTask(item)
})
stream.on('error', function (err) {
console.error(err)
})
stream.on("end", function() {
console.log("DONE!")
db.close()
})
})
上面的代码运行了大约 15 秒,检索了 6000 到 8000 个文档,然后抛出以下错误:
{ MongoError: cursor does not exist, was killed or timed out
at queryCallback (/Volumes/safezone/development/workspace-router/migration/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js:136:23)
at /Volumes/safezone/development/workspace-router/migration/node_modules/mongodb-core/lib/connection/pool.js:541:18
at process._tickCallback (internal/process/next_tick.js:150:11)
name: 'MongoError',
message: 'cursor does not exist, was killed or timed out' }
我需要检索大约 50000 个文档,因此我需要找到一种方法来避免光标超时。
如上面的代码所示,我尝试增加socketTimeoutMS 和connectTimeoutMS,这对光标超时没有影响。
我也尝试将stream 替换为forEach 并添加.addCursorFlag('noCursorTimeout', true),但这也没有帮助。
我已经尝试了我发现的关于 mongodb 的所有内容,我没有尝试过 mongoose 或替代方案,因为它们使用模式,我稍后必须更新属性的当前类型(这对于 mongoose 模式可能很棘手) .
【问题讨论】: