'Typing mongo collection with a generic

I have a generic class with some mongo methods.

export class Repository<T> {
  private connection: MongoClient | undefined;

  constructor(private collectionName: string, private schema: Schema<T>) {}

  collection(): Collection<T> {
    if (!this.connection) {
      throw new Error(
        `You must first make a connection to the database for ${this.collectionName} collection.`
      );
    }

    return this.connection.db().collection<T>(this.collectionName);
  }

  async exists(id: string): Promise<boolean> {
    const collection = this.collection();
    const doc = await collection.findOne<T>({ _id: new ObjectId(id) });
    return !!doc;
  }
}

To this class I pass a generic which I use to type the collection.

The problem is that when doing, for example, a findOne, I have the following Typescript error and I don't understand why.

Do I have to extend the generic with some kind of mongo?

enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source