Nodejs mongodb驱动程序在客户端关闭时挂起

问题描述 投票:0回答:1

我有以下代码,并且不明白为什么我的进程挂在试图关闭与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');
    }
}

提前感谢您的帮助!

node.js mongodb database-connection
1个回答
0
投票
请确保您使用的是最新版本的mongodb,因为较早的版本存在一个错误,其中的bulkWrite方法由于此处提到的某些错误-https://stackoverflow.com/a/46700933/1021796而静默失败->

在尝试关闭连接之前,您还可以检查它是否已连接。因此代码将是

if (client.isConnected) { await client.close(); }

希望这会有所帮助
© www.soinside.com 2019 - 2024. All rights reserved.