mongodb/node-mongodb-native · error · MongoInvalidArgumentError

Operation passed in cannot be an Array

Error message

Operation passed in cannot be an Array

What it means

Thrown by OrderedBulkOperation.addToOperationsList() when the document argument is an array. Each addToOperationsList call must receive a single operation document; arrays of operations must be enqueued one at a time. The check runs after size validation, so the error is reached for array inputs that are not already rejected.

Source

Thrown at src/bulk/ordered.ts:88

      // Create a new batch
      this.s.currentBatch = new Batch(batchType, this.s.currentIndex);

      // Reset the current size trackers
      this.s.currentBatchSize = 0;
      this.s.currentBatchSizeBytes = 0;
    }

    if (batchType === BatchType.INSERT) {
      this.s.bulkResult.insertedIds.push({
        index: this.s.currentIndex,
        _id: (document as Document)._id
      });
    }

    // We have an array of documents
    if (Array.isArray(document)) {
      throw new MongoInvalidArgumentError('Operation passed in cannot be an Array');
    }

    this.s.currentBatch.originalIndexes.push(this.s.currentIndex);
    this.s.currentBatch.operations.push(document);
    if (buffer != null) this.s.currentBatch.serializedOperations.push(buffer);
    this.s.currentBatchSize += 1;
    this.s.currentBatchSizeBytes += maxKeySize + bsonSize;
    this.s.currentIndex += 1;
    return this;
  }
}

View on GitHub (pinned to 3366c21a63)

Solutions

  1. Iterate and call addToOperationsList once per document.
  2. Use bulk.insert(doc) in a loop rather than passing the whole list.
  3. If you have a list, use collection.bulkWrite(ops) which handles iteration internally.

Example fix

// before
addToOperationsList(BatchType.INSERT, [docA, docB]);

// after
for (const doc of [docA, docB]) addToOperationsList(BatchType.INSERT, doc);
Defensive patterns

Strategy: type-guard

Validate before calling

function assertSingleDoc(doc) {
  if (Array.isArray(doc)) {
    throw new TypeError('addToOperationsList expects a single document, not an array');
  }
}

Type guard

function isSingleDocument(doc) {
  return doc != null && typeof doc === 'object' && !Array.isArray(doc);
}

Try / catch

try {
  addToOperationsList(batchType, doc);
} catch (e) {
  if (/cannot be an Array/.test(e.message)) {
    for (const d of doc) addToOperationsList(batchType, d);
  }
}

Prevention

When it happens

Trigger: Internally calling addToOperationsList(batchType, [...]) with an array. A code path that passes a list of documents instead of iterating. Generally not user-reachable via the fluent API but possible via internal misuse or extensions.

Common situations: Custom subclasses or middleware that intercept addToOperationsList and pass arrays; misuse of internal APIs.

Related errors


AI-assisted analysis of mongodb/node-mongodb-native@3366c21a63 (2026-08-04). Data as JSON: /data/errors/1b398d0afa50f732.json. Report an issue: GitHub.