Skip to content

Type error if an object with type 'any' is passed to the model's create method (Typescript) #11970

@artemkosenko

Description

@artemkosenko

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

6.4.0

Node.js version

16.15.0

MongoDB server version

5.x

Description

The 'create' method returns wrong object type if the prototype passed to it is of type 'any'

Steps to Reproduce

A code snippet to reproduce.

export interface ImportantObject extends BaseSchema {
    field_one: string;
    field_two: string;
}

const importantObjectSchema = new Schema({
    field_one: {type: String, required: true},
    field_two: {type: String, required: true},
}, {_id: false});

export const ImportantObjectModel = mongoose.model<ImportantObject>("important_objects", importantObjectSchema);


const createOne = async (field_one: string, field_two: string): Promise<ImportantObject> => {
    /* any type is to reproduce the issue */
    const proto: any = {
        field_one,
        field_two
    }
    /*
     TS2740: Type 'Document  { _id: any; }>>> & Omit { _id: any; }> & { _id: ObjectId; }' is missing the following properties from type 'ImportantObject': field_one, field_two, owner, group, and 8 more.
    */
    const new_one: ImportantObject = await ImportantObjectModel.create(proto);
    return new_one;
}

image

Workaround

  1. Stick to mongoose ~6.3.x
  2. add // @ts-ignore

Expected Behavior

A correct type must be returned.

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