我有以下代码,并且无法理解为什么我的进程挂在试图关闭与mongodb的连接的行上,这是我的代码:
async function save(clientCredentials, newFieldsToUpdate){
const url = `mongodb://${clientCredentials.username}:${clientCredentials.password}@my.server.ip:22222/${clientCredentials.database}`
const client = await MongoClient.connect(url, {useNewUrlParser:true, useUnifiedTopology: true})
.catch(err => { console.log(err); });
const db = client.db(clientName);
const collection = await db.collection("products");
let execute = false;
const updateOps = [];
for(let objectIdentifier in newFieldsToUpdate){
let updateOperation = {};
updateOperation['$set'] = newFieldsToUpdate[objectIdentifier];
let id = mongodb.ObjectID(objectIdentifier);
execute = true;
updateOps.push({ updateOne: { filter: {_id: id}, update: {$set: newFieldsToUpdate[objectIdentifier]}, upsert:true } })
}
if(execute){
try {
console.log('executing'); // I see this line
let report = await collection.bulkWrite(updateOps);
console.log('executed'); // I see this line
await client.close();
console.log('closed conn'); // I don't see this line! why? it's weird
return report;
} catch(ex){
console.error(ex);
}
} else {
console.log('not executing');
}
}
在此先感谢您的帮助!
编辑:批量操作仅包含大约200个文档,如果我尝试使用单个文档,这很奇怪。节点版本3.3.2的Mongodb驱动程序
EDIT2:我注意到在mongo connect上使用参数poolSize:1可以成功关闭连接,但是使用默认的poolSize 5并不能关闭连接,这有什么建议吗?
答案 0 :(得分:1)
请确保您使用的是最新版本的mongodb
驱动程序(请确保删除node_modules),因为较早的版本存在一个错误,其中bulkWrite
方法由于此处提到的某些错误而静默地失败了-{{ 3}}
在尝试关闭连接之前,还应检查它是否已连接。因此代码将是
if (client.isConnected) {
await client.close();
}
希望这会有所帮助