Skip to content

Excluding _id and including another prop in projection returns TS error #15431

Closed
@DavideViolante

Description

@DavideViolante

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.15.0

Node.js version

22.x

MongoDB server version

idk

Typescript version (if applicable)

5.8.3

Description

I've the same bug reported also here by @msalafia
Note also my next comment there.
The bug is related to that PR changes.

In my project I have the error on this line:

const items = await User.find({}, { lastName: 1, _id: 0 });

Either if I remove lastName or _id it works, but is not the intended projection I want.

Error:

No overload matches this call.
  Overload 1 of 5, '(filter: RootFilterQuery<IUser>, projection?: ProjectionType<IUser>, options?: QueryOptions<IUser>): Query<...>', gave the following error.
    Type '0' is not assignable to type 'true | 1'.
  Overload 2 of 5, '(filter: RootFilterQuery<IUser>, projection?: ProjectionType<IUser>): Query<(Document<unknown, {}, IUser, {}> & IUser & Required<...> & { ...; })[], ... 4 more ..., {}>', gave the following error.
    Type '0' is not assignable to type 'true | 1'.ts(2769)

Steps to Reproduce

const items = await User.find({}, { lastName: 1, _id: 0 });

Schema:

import { Document, model, Schema, Types } from 'mongoose';

const userSchema = new Schema<IUser>({
  username: { type: String, trim: true },
  firstName: { type: String, required: true, trim: true },
  lastName: { type: String, required: true, trim: true },
  // ...
});

export interface IUser extends Document {
  _id: Types.ObjectId;
  username: string;
  firstName: string;
  lastName: string;
  // ...
}

const User = model<IUser>('User', userSchema);

export default User;

Expected Behavior

Ability to use _id: 0 and another prop.

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.typescriptTypes or Types-test related issue / Pull Request

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions