Skip to content

TypeScript Error: FilterQuery with string _id not assignable to PipelineStage $match in Mongoose 9.1.5 #16006

@naveenkarmegam

Description

@naveenkarmegam

Description
When using FilterQuery<T> where T is an interface with _id: string (not ObjectId), passing this filter object to an aggregation pipeline's $match stage causes a TypeScript error in Mongoose 9.1.5.
The error suggests that RootFilterOperators expects _id to be compatible with ObjectId (or ApplyBasicQueryCasting<ObjectId>), but the interface explicitly defines it as string, causing an incompatibility even if _id is not present in the filter object.

Steps to Reproduce

  1. Define an interface with _id: string.
  2. Create a FilterQuery object for that interface.
  3. specific the filter query to a $match stage in an aggregation pipeline.

Reproduction Script

import { FilterQuery, PipelineStage } from 'mongoose';

interface MyDoc {
  _id: string; // strict string, not ObjectId
  name: string;
}

const matchCriteria: FilterQuery<MyDoc> = {
  name: 'test'
};

// Error occurs here
const pipeline: PipelineStage[] = [
  {
    $match: matchCriteria
  }
];

Expected Behavior
The FilterQuery should be assignable to the $match stage input, as _id as a string is a valid use case (e.g. user-defined string IDs).

Error Output

Type '_QueryFilter<...>' is not assignable to type 'RootFilterOperators<{ [x: string]: any; _id?: ApplyBasicQueryCasting<ObjectId> | undefined; }>'
...
Types of property '_id' are incompatible.
  Type 'Condition<string | RegExp | string[] | null> | undefined' is not assignable to type 'Condition<((string | Types.ObjectId | ObjectId | ObjectId[] | undefined) & (string | Types.ObjectId | ObjectId | ObjectId[])) | null> | undefined'.

Versions

  • Mongoose: 9.1.5
  • TypeScript: 5.9.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions