mongoose: TypeScript errors with .lean() after upgrading from Mongoose 8.7.1 to 8.7.2

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

8.7.2

Node.js version

20.15.1

MongoDB server version

7.0.14

Typescript version (if applicable)

5.6.3

Description

Hi Mongoose team,

After upgrading Mongoose from version 8.7.1 to 8.7.2, I’m encountering TypeScript errors when running queries that use the .lean() method. The issue seems to be related to changes in the type utility chain, specifically in how FlattenMaps and BufferToBinary are applied.

Here’s the TypeScript error:

The types of 'options.session' are incompatible between these types.
Type 'Binary | null | undefined' is not assignable to type 'Buffer<ArrayBufferLike> | undefined'.
Type 'null' is not assignable to type 'Buffer<ArrayBufferLike> | undefined'.ts(2322)

Code that previously ran without issues, such as:

const blogs: Blog[] = await BlogModel.find({ status: BlogStatus.Published })
  .select('slug language')
  .lean()
  .exec();

or

const account: Account | null = await AccountModel.findById(accountId)
  .select('-hashedPassword -mfa -oauthId')
  .lean()
  .exec();

is now throwing the above TypeScript error.

Previously, the type chain in mongoose\types\query.d.ts was:

Require_id<FlattenMaps<BufferToBinary<RawDocType>>>

in the code:

  type GetLeanResultType<RawDocType, ResultType, QueryOp> = QueryOp extends QueryOpThatReturnsDocument
    ? (ResultType extends any[] ? Require_id<FlattenMaps<BufferToBinary<RawDocType>>>[] : Require_id<FlattenMaps<BufferToBinary<RawDocType>>>)
    : ResultType;

But after the update, the order of FlattenMaps and BufferToBinary has been swapped to:

Require_id<BufferToBinary<FlattenMaps<RawDocType>>>

like:

  type GetLeanResultType<RawDocType, ResultType, QueryOp> = QueryOp extends QueryOpThatReturnsDocument
    ? (ResultType extends any[] ? Require_id<BufferToBinary<FlattenMaps<RawDocType>>>[] : Require_id<BufferToBinary<FlattenMaps<RawDocType>>>)
    : ResultType;

This change appears to have introduced stricter typing or structural mismatches in queries that return lean documents, particularly when using .lean<T>() or .lean() without explicit typing. The flipping of FlattenMaps and BufferToBinary seems to cause issues when dealing with Map or Buffer fields in the schema. I think this is breaking change, and should be reverted.

Steps to Reproduce

  1. Use Mongoose 8.7.1 and run a similar query like:
const blogs: Blog[] = await BlogModel.find({ status: BlogStatus.Published })
  .select('slug language')
  .lean()
  .exec();

or

const account: Account | null = await AccountModel.findById(accountId)
	.select('-hashedPassword -mfa -oauthId')
	.lean()
	.exec();

This will run without issues.

  1. Upgrade to Mongoose 8.7.2

  2. Run the same queries, and then TypeScript will show an error.

Expected Behavior

Expected Behavior:

Queries using .lean() should return plain objects that conform to the expected TypeScript interface (e.g., Blog[] in the case of a Blog model) without any TypeScript errors, as it worked in version 8.7.1.

As a workaround, I’ve had to explicitly type the result of .lean<T>(), but this was not required in previous versions:

const blogs: Blog[] = await BlogModel.find({ status: BlogStatus.Published })
  .select('slug language')
  .lean<Blog>()
  .exec();

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 9
  • Comments: 19

Most upvoted comments

I can say the issue is still present, when using lean our project typescript breaks, I don’t think it’s right that this issue was closed, the new version just breaks an entire project

@hasezoey, the modifications in schema.test.ts seem directly related to supporting the new type definitions. If those tests had not been updated, they likely would have failed, indicating a shift in how consumers should interact with Mongoose. This reinforces the idea that the changes are significant.

@vkarpov15, while I understand that these updates may provide useful improvements, I hope that future changes, even if they enhance current functionality, will adhere to Semantic Versioning best practices. This will ensure a smoother experience for all users and maintain trust in the library’s stability. If such changes continue to occur, we will likely keep facing issues like this. I reported something similar two months ago: https://github.com/Automattic/mongoose/issues/14863, and it seems I’m not alone, as @richardsimko mentioned.

Thank you, guys, for the discussion! I learned a lot about Mongoose along the way.

const test: FooDocument[] = await FooModel.find({ bar: 'asd' }).lean(); should be const test: Foo[] = await FooModel.find({ bar: 'asd' }).lean();. The whole point of lean() is that it returns the raw Foo document, without any Mongoose functionality.

“what do you think about reverting the mention change?”

I think we should not revert this change. The line between a bug fix and a breaking change can get blurry, especially when users rely on incorrect behavior. However, in this case, I think the TypeScript types are doing their job by highlighting code that is objectively incorrect. If you’re expecting _id to be of type mongoose.ObjectId or expecting lean() to return a hydrated Mongoose document, then you’re going to run into runtime errors.

You can always work around this issue using lean()'s generic param: const test: FooDocument[] = await FooModel.find({ bar: 'asd' }).lean<FooDocument[]>(), although I would only recommend that as a temporary workaround.

@hasezoey Thanks, that did indeed resolve the issue I had.

@Towerss I created #15017 and will try to work on it myself in the coming days/weeks to try and improve TS testing as we’ve also experienced what you describe with a lot of breaking TS changes being shipped in non-major releases.

@vkarpov15 As others have pointed out this issue isn’t actually solved by your recommended solution and should be reopened. Here is the same repro with your suggested change which still throws an error.

import { Schema, model } from 'mongoose';

import type { Document, Types } from 'mongoose';

export interface Foo {
  _id: Types.ObjectId;
  bar: string;
}
export type FooDocument = Foo & Document<Types.ObjectId>;

const schema = new Schema<Foo>(
  {
    bar: { type: String, required: true },
  },
  { collection: 'foo', timestamps: true },
);

export const FooModel = model<Foo>('foo', schema);

const test: FooDocument[] = await FooModel.find({ bar: 'asd' }).lean();

Image

I’m again asking for a #14967 to be reverted until a stable solution has been found, as others have mentioned this is a breaking change that was released as a patch version and should be rolled back.

@Towerss

(original issue description)

Previously, the type chain in mongoose\types\query.d.ts was: Require_id<FlattenMaps<BufferToBinary<RawDocType>>>

(later comment)

This seems to be related to the changes in the type utility chain, specifically the swapping of FlattenMaps and BufferToBinary in mongoose/types/query.d.ts Previously, the type chain was: Require_id<FlattenMaps<BufferToBinary<RawDocType>>> But in version 8.7.2, it has changed to:

just wanna point out that #14967 completely added the new BufferToBinary type

This is how the lean type was in tag 8.7.1: https://github.com/Automattic/mongoose/blob/02c5efd7ee19eca0f0e5744719b36e19cba0f58d/types/query.d.ts#L213-L215

I believe the change introduced in version 8.7.2 has inadvertently caused a breaking change in the TypeScript typings

to my knowledge in mongoose any type change can be in any version, though it had mostly stabilized since 7.x (speaking from a typegoose upgrade perspective)


i also wanna point out that the examples from this comment and this comment want to assign a lean type to a document type. A lean type does not have anything from type mongoose.Document anymore (aside from the extra properties like _id and __v, etc).

A fixed version could look like:

/* eslint-disable @typescript-eslint/no-unused-vars */
// NodeJS: 22.8.0
// Typescript 5.3.3
import * as mongoose from 'mongoose'; // mongoose@8.8.0

interface Foo {
  _id: mongoose.Types.ObjectId;
  bar: string;
}
type FooDocument = Foo & mongoose.Document<mongoose.Types.ObjectId>;
type FooLean = mongoose.GetLeanResultType<Foo, Foo, unknown>;

const schema = new mongoose.Schema<Foo>(
  {
    bar: { type: String, required: true },
  },
  { collection: 'foo', timestamps: true }
);

const FooModel = mongoose.model<Foo>('foo', schema);

async function main() {
  const test1: FooLean[] = await FooModel.find({ bar: 'asd' }).lean();
  const test2: Foo[] = await FooModel.find({ bar: 'asd' }).lean();
  // const test3: FooDocument[] = await FooModel.find({ bar: 'asd' }).lean();
}

main();

(Reproduction repository & branch)


If the issue still persists when removing the Document from the types, please provide new / updated reproduction code (and error output for quicker look-over)

There doesn’t seem to be a good way to make it so that _id: ObjectId as opposed to _id: Types.ObjectId fails to compile with a cleaner error message. But either way, the fix is to replace:

export interface Foo {
  _id: ObjectId;
  bar: string;
}

with:

export interface Foo {
  _id: Types.ObjectId;
  bar: string;
}

because mongoose.ObjectId is not the runtime ObjectId type.

Binary is slightly different from Buffer. The error message makes it seem like Mongoose is converting some internal type’s Buffer properties into Binary when it shouldn’t. I’m investigating, but haven’t found an explanation yet.

Seeing the same thing, probably related to #14902 and #14967

Here is a fully reproducible example which worked in 8.7.1:

import { Schema, model } from 'mongoose';

import type { Document, ObjectId } from 'mongoose';

export interface Foo {
  _id: ObjectId;
  bar: string;
}
export type FooDocument = Foo & Document<ObjectId>;

const schema = new Schema<Foo>(
  {
    bar: { type: String, required: true },
  },
  { collection: 'foo', timestamps: true },
);

export const FooModel = model<Foo>('foo', schema);

const test: FooDocument[] = await FooModel.find({ bar: 'asd' }).lean();
core/models/test.ts:20:7 - error TS2322: Type '({ _id: { auto: (turnOn: boolean) => ObjectId; defaultOptions: { [x: string]: any; }; OptionsConstructor: { [x: string]: any; type?: any; alias?: string | string[]; validate?: Function | ... 6 more ... | readonly (Function | ... 4 more ... | { ...; }[])[]; ... 28 more ...; maxlength?: number | ... 1 more ... | reado...' is not assignable to type 'FooDocument[]'.
  Type '{ _id: { auto: (turnOn: boolean) => ObjectId; defaultOptions: { [x: string]: any; }; OptionsConstructor: { [x: string]: any; type?: any; alias?: string | string[]; validate?: Function | ... 6 more ... | readonly (Function | ... 4 more ... | { ...; }[])[]; ... 28 more ...; maxlength?: number | ... 1 more ... | readon...' is not assignable to type 'FooDocument'.
    Type '{ _id: { auto: (turnOn: boolean) => ObjectId; defaultOptions: { [x: string]: any; }; OptionsConstructor: { [x: string]: any; type?: any; alias?: string | string[]; validate?: Function | ... 6 more ... | readonly (Function | ... 4 more ... | { ...; }[])[]; ... 28 more ...; maxlength?: number | ... 1 more ... | readon...' is not assignable to type 'Foo'.
      The types of '_id.OptionsConstructor.index' are incompatible between these types.
        Type 'boolean | IndexDirection | { expires?: string | number; weights?: { [x: string]: number; }; background?: boolean; unique?: boolean; name?: string; partialFilterExpression?: { ...; }; ... 38 more ...; explain?: ExplainVerbosityLike; }' is not assignable to type 'boolean | IndexDirection | IndexOptions'.
          Type '{ expires?: string | number; weights?: { [x: string]: number; }; background?: boolean; unique?: boolean; name?: string; partialFilterExpression?: { [x: string]: any; }; sparse?: boolean; expireAfterSeconds?: number; ... 36 more ...; explain?: ExplainVerbosityLike; }' is not assignable to type 'boolean | IndexDirection | IndexOptions'.
            Type '{ expires?: string | number; weights?: { [x: string]: number; }; background?: boolean; unique?: boolean; name?: string; partialFilterExpression?: { [x: string]: any; }; sparse?: boolean; expireAfterSeconds?: number; ... 36 more ...; explain?: ExplainVerbosityLike; }' is not assignable to type 'IndexOptions'.
              The types of 'session.clientOptions.autoEncryption.keyVaultClient.options.session' are incompatible between these types.
                Type 'Binary' is missing the following properties from type 'Buffer': slice, subarray, equals, compare, and 93 more.
20 const test: FooDocument[] = await FooModel.find({ bar: 'asd' }).lean();
         ~~~~