Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.88k stars 3.83k forks source link

insertMany return type incompatible with document type #13999

Closed ksyd9821 closed 9 months ago

ksyd9821 commented 11 months ago

Prerequisites

Mongoose version

7.6.3

Node.js version

18.x

MongoDB server version

6.x

Typescript version (if applicable)

5.2.2

Description

This is the same issue previously reported in #13957 I have included the code that reproduces it below. Basically with the code below

import * as mongoose from "mongoose";

export class RepositoryBase<T> {
    protected model: mongoose.Model<T & mongoose.Document>;

    constructor(schemaModel: mongoose.Model<T & mongoose.Document>) {
        this.model = schemaModel;
    }

    async insertMany(elems: T[]): Promise<T[]> {
        elems = await this.model.insertMany(elems);
        return elems;
    }
}

the assignment inside the insertMany function generates the following error image

Steps to Reproduce

https://github.com/ksyd9821/mongoose-insert-many-issue

Expected Behavior

No response

### Tasks
vkarpov15 commented 10 months ago

Just remove the & Document and this script compiles fine:

import * as mongoose from "mongoose";

export class RepositoryBase<T> {
    protected model: mongoose.Model<T>;

    constructor(schemaModel: mongoose.Model<T>) {
        this.model = schemaModel;
    }

    async insertMany(elems: T[]): Promise<T[]> {
        elems = await this.model.insertMany(elems);
        return elems;
    }
}

As of Mongoose 7, we no longer support using extends Document in the DocType generic param to Model<>, and we recommend using the raw doc type instead. So don't use & Document.

hardcodet commented 9 months ago

Hi @vkarpov15

Just stumbled over this one. Is it possible that there is an overload missing here (we're on 8.0.0. currently)? Your snippet works, but not, if I provide an options object. See the inferred types in the screenshot here - bar here doesn't properly cast to T[], while foo works.

image

Let me know if you'd prefer a new issue. (I also don't know if you'll read this, since it's already closed, so I might open a new issue in a few days anyway).