Skip to content

Querying with { _id: undefined } causes "Multiple body sections in message" error #692

Description

@marcj

Description

When executing a query with undefined as a filter value (e.g., { _id: undefined }), the MongoDB driver produces a malformed wire protocol message instead of either:

  • Throwing a validation error before sending the query
  • Handling it gracefully (treating as "match nothing" or converting to { _id: null })

Reproduction

  import { Database } from '@deepkit/orm';
  import { MongoDatabaseAdapter } from '@deepkit/mongo';

  const database = new Database(new MongoDatabaseAdapter('mongodb://localhost:27017/test'));

  // This causes the error:
  const result = await database.query(SomeEntity)
    .filter({ _id: undefined })
    .findOneFieldOrUndefined('someField');

Error

  MongoDatabaseError: Multiple body sections in message, on connection localhost:27017 (standalone)
      at handleErrorResponse (/node_modules/@deepkit/mongo/src/client/error.ts:23:30)
      at FindCommand.handleResponse (/node_modules/@deepkit/mongo/src/client/command/command.ts:136:39)
      at MongoConnection.onResponse (/node_modules/@deepkit/mongo/src/client/connection.ts:885:34)
      at BsonStreamReader.feed (/node_modules/@deepkit/bson/src/stream.ts:67:22)
      ...

Expected Behavior

Either:

  1. Validation error before sending to MongoDB: "Cannot use undefined as filter value for field '_id'"
  2. Graceful handling: Treat undefined values as "no match" or strip them from the filter

Environment

  • @deepkit/mongo: [version]
  • @deepkit/orm: [version]
  • MongoDB: 7.x / 8.x
  • Node.js: 20.x / 22.x

Workaround

Guard against undefined before querying:

  if (entityId) {
    const result = await database.query(SomeEntity)
      .filter({ _id: entityId })
      .findOneFieldOrUndefined('someField');
  }

Analysis

The issue appears to be in BSON serialization - undefined values are being serialized in a way that produces an invalid MongoDB wire protocol message, causing the server to reject it with "Multiple body sections in
message".

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions