我正试图更新一个DB中多个集合中的多个文档。当这样做的时候,Mongo在第一个集合之后抛出一个错误。并且不对后面的文件进行修改。
错误
断言失败。MongoError: 不能使用已经结束的会话
const migration = async function migrate(client, dbName) {
const engineDatabase = client.db(dbName);
console.log(`connected to db ${engineDatabase.databaseName}`);
const collections = await engineDatabase.collections();
for (const collection of collections) {
console.log(collection.collectionName);
collection.updateMany({}, {$set: {"ownerIds": ["-1", "1"]}}, function (err, res) {
console.assert(err == null, err);
console.log(res.result.nModified + " document(s) updated");
}
)
}
};
module.exports = migration;
我必须在每次更新后关闭客户端吗?还是要等下一次更新?我不明白这个错误有什么意义。
这一部分是异步的
collection.updateMany({}, {$set: {"ownerIds": ["-1", "1"]}}, function (err, res) {
console.assert(err == null, err);
console.log(res.result.nModified + " document(s) updated");
})
发生了什么事,你的程序正在完成,而你的程序正在完成 updateMany
还没有完成。
而你已经在使用 async/await
,你不需要在那里有一个回调。
你可以改用
const res = await collection.updateMany({}, {$set: {"ownerIds": ["-1", "1"]}});
console.log(res.result.nModified + " document(s) updated");