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
- 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.
-
Upgrade to Mongoose 8.7.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
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 beconst test: Foo[] = await FooModel.find({ bar: 'asd' }).lean();. The whole point oflean()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
_idto be of typemongoose.ObjectIdor expectinglean()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.
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)
(later comment)
just wanna point out that #14967 completely added the new
BufferToBinarytypeThis is how the lean type was in tag 8.7.1: https://github.com/Automattic/mongoose/blob/02c5efd7ee19eca0f0e5744719b36e19cba0f58d/types/query.d.ts#L213-L215
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.Documentanymore (aside from the extra properties like_idand__v, etc).A fixed version could look like:
(Reproduction repository & branch)
If the issue still persists when removing the
Documentfrom 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: ObjectIdas opposed to_id: Types.ObjectIdfails to compile with a cleaner error message. But either way, the fix is to replace:with:
because
mongoose.ObjectIdis 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: