To efficiently delete multiple documents, you can first create a query object for the deletion process and use it to fetch the targeted documents using find
. Once you have retrieved all the necessary documents, you can proceed to delete them using deleteMany
.
If the count of deleted documents matches the total fetched document count, you can safely remove all references from the author's list. However, if the counts do not match, you will need to iterate through the initially-fetched documents, attempt to fetch each one again, and if it is not found, then it has been deleted and can be safely removed from the author.
Here is an example in TypeScript:
const queryObj = { foo: 'bar' };
const postsCollection = mongoDb.getCollection<{ _id: ObjectId }>('posts');
const postsToDelete = await postsCollection.find(queryObj).toArray();
const deleteManyResult = await postsCollection.deleteMany(queryObj);
if (deleteManyResult.deletedCount === postsToDelete.length) {
for (const deletedPost of postsToDelete) {
// delete from author
}
} else {
for (const potentiallyDeletedPost of postsToDelete) {
const post = await postsCollection.findOne({ _id: potentiallyDeletedPost._id });
if (!post) {
// delete from author
} else {
// handle non-deleted post
}
}
}