Skip to content

TypeScript error when passing { _id: ids } or { _id: arrayOfDocs } to FilterQuery #10826

Closed
@ahmedelshenawy25

Description

@ahmedelshenawy25

Do you want to request a feature or report a bug?
Bug

What is the current behavior?
TypeScript compilation error if _id is given an array of ids or documents in FilterQuery

Type '(Document<any, any, IBook> & IBook & { _id: string | ObjectId; })[]' is not assignable to type 'Condition<string | ObjectId> | undefined'.
  Type '(Document<any, any, IBook> & IBook & { _id: string | ObjectId; })[]' is not assignable to type 'string'
Type '(string | ObjectId)[]' is not assignable to type 'Condition<string | ObjectId> | undefined'.
  Type '(string | ObjectId)[]' is not assignable to type 'string'.

If the current behavior is a bug, please provide the steps to reproduce.

import mongoose, { Types } from 'mongoose';

interface IBook {
  _id: Types.ObjectId | string;
  name: string;
}

async function run() {
  await mongoose.connect('mongodb://localhost:27017/test');

  const bookSchema = new mongoose.Schema<IBook>({
    name: { type: String, required: true }
  });

  const Book = mongoose.model<IBook>('Book', bookSchema);

  await Book.create([{ name: 'aaa' }, { name: 'aaa' }]);

  const books = await Book.find({});
  const booksIds = books.map((book: IBook) => book._id);

  await Book.updateMany({ _id: books }, { name: 'bbb' });
  await Book.updateMany({ _id: booksIds }, { name: 'ccc' });

  console.log('Done');
}

run().catch(console.error);
{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

What is the expected behavior?
It should pass compilation since mongoose transforms FilterQuery into { _id :{ $in: ids} }

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.
Node.js: v14.15.5
Mongoose: v6.0.8
MongoDB: v4.4.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    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