我的代码是从mongo集合中流式传输数据,并在对其进行一些操作后将其插入另一个数据库。
在关闭数据库连接之前,我似乎无法找到等待操作整个数据的方法。在流“关闭”后的几秒钟内完成数据的处理。我想等待所有数据 关闭数据库连接之前要完成的操作。我怎么做?
PS:我确实看到所有数据都已被操作。这很好用。但我想关闭数据库连接。在做这个之前我需要等待所有操作完成!
var count = 0; // Counter for number of mongo docs that has been inserted in new_db
mongo_db.collection(config.collection, function (err, coll) {
coll.find(config.mongo_query).count(function (e, coll_docs_count) {
var stream = coll.find(config.mongo_query).stream();
stream.on('close', function () {
if (count === coll_docs_count) {
// This NEVER executes since the data is finished
//being operated and inserted in the NEW DB a few seconds after
//this moment.
mongo_client.close();
cb_bucket.disconnect();
}
});
stream.on('data', function (doc) {
... // Do some operations on it
new_db.insert(doc, function (blah blah) {
count++;
})
})
})
})