Reputation: 400
I am trying to update multiple documents in multiple collections in a DB. While doing that Mongo throws an error after the first collection. And doesn't make changes on the after ones.
Error
Assertion failed: MongoError: Cannot use a session that has ended
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;
Do I have to close the client after every update? Or do I have to wait for the next update? I couldn't get what's the point of this error.
Upvotes: 2
Views: 2522
Reputation: 1244
This part is asynchronous
collection.updateMany({}, {$set: {"ownerIds": ["-1", "1"]}}, function (err, res) {
console.assert(err == null, err);
console.log(res.result.nModified + " document(s) updated");
})
Whats happening is your program is finishing while the updateMany
is not yet done.
And you're already using async/await
, you don't need to have a callback there.
You can instead do
const res = await collection.updateMany({}, {$set: {"ownerIds": ["-1", "1"]}});
console.log(res.result.nModified + " document(s) updated");
Upvotes: 1