How to check if BulkOp is empty or not

This used to work:

const bulkOp = writeCollection.initializeUnorderedBulkOp();

if (bulkOp.length > 0) bulkOp.execute();

But for some reason the length property is gone in later MongoDB drivers. So how to properly check if bulkOp contains operations before calling execute? Because simply calling execute on an empty Bulk, throws an error: Invalid BulkOperation, Batch cannot be empty.

However if I cannot check if that Bulk is empty, how can I possibly know? Help :slight_smile:

Hi Mar! Thank you for your question!

bulkOp.length works for me with the latest Node.js Driver - version 6.8.0. Also note that bulkOp.execute() is an async function.

Which driver and version are you using?

I’m using node and mongodb version is 6.8.0

// @ts-ignore
if (bulkOp.length >= batchSize) {
	const res = await bulkOp.execute();

this is my code, which works. However without the // @ts-ignore, TypeScript generates an error:

Property ‘length’ does not exist on type ‘UnorderedBulkOperation’.

So it ‘thinks’ it doesn’t exist, but in fact it does.

Good catch! I’ll check internally if length was intentionally made private or not.

You may use bulkOp.batches.length which is public.

if (bulkOp.batches.length > 0) {
  await bulkOp.execute();

The batches getter is defined in the BulkOperationBase interface.

We indeed overlooked this issue when upgrading the Node.js Driver. Thank you for bringing it up on the Community Forums!

We have just merged the pull request with the fix. The fix will be included in the next driver release. I’ll post an update here once it’s available.

1 Like