[英]How can i close mongo connection after all db-operations done in for-each?
問題:- 在Node Async Programming
中完成操作之前關閉數據庫連接。
AIM:-打開數據庫連接,將 Static Json 文件寫入 db collections 並關閉連接.. 在節點服務器啟動之前。
Collections:-25 和里面的許多文件所以使用 db.insertMany()
代碼示例:-
async function run(){
try{
let path = '../some';
//avoiding common db configurations
await client.connect();
//..Couple of DB initializatoins ...
db1.dropDataBase();
db2.dropDataBase()
// for reading Data from the Directory
fs.readDirSync(dirPath).forEach(file => {
let collectionName = path.base(file,'.json');
(()=>{
if(collectionName === 'test')
{
let count = await db1.collectionName.estimatedDocumentCount();
let jsonContent = JSON.parse(fs.readDirSync(path.join(DirectoryPath,file),'utf-8'));
if(count===0){
await db1.collectionName.insertMany(jsonContent);
}
}
else{
let count = await db2.collectionName.estimatedDocumentCount();
let jsonContent = JSON.parse(fs.readDirSync(path.join(DirectoryPath,file),'utf-8'));
if(count===0){
await db2.collectionName.insertMany(jsonContent);
}
}
})(file);
})
}
catch(err){
console.log('error',err);
}
finally
{
console.log('Closing DB connection');
client.close();
}
} run().catch(console.dir);
Output :-
Closing DB connection
error cannot use a Session which is already ended
error cannot use a Session which is already ended
error cannot use a Session which is already ended
注意:-如果我評論db.close()
它就像一個 Charm,但我無法啟動node app.js
,因為它在 DB 程序本身中停止了。
完成所有操作后如何關閉連接? 我在這里被困住了:-(幫助!!
首先,您應該從 finally 中刪除 client.close() 。 這將在第一次循環迭代后調用,以防止您進行進一步處理。
然后使用您的 forEach 循環創建一個函數數組並使用名為 Promise.all 的方法
var actions = [p1,p2,..] //populate this with your insert functions as promises
Promise.all().then(function() {
// all loaded
client.close();
}, function() {
// one or more failed
client.close();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.