Skip to content

Export EnforceDocument<> from TypeScript types, rename it to something more user-friendly #10843

@Bene-Graham

Description

@Bene-Graham

If we take a slightly modified version of: https://mongoosejs.com/docs/typescript.html

import { Schema, model, connect } from 'mongoose';

interface User {
    name: string;
    email: string;
    avatar?: string;
}

const schema = new Schema<User>({
    name: { type: String, required: true },
    email: { type: String, required: true },
    avatar: String
});

const UserModel = model<User>('User', schema);

run().catch(err => console.log(err));

function print(entity: /* WHAT GOES HERE??? */) {
    console.log(`${entity._id} -- ${entity.name}`);
}

async function run(): Promise<void> {
    // 4. Connect to MongoDB
    await connect('mongodb://localhost:27017/test');

    const userEntity = await UserModel.findOne().exec();
    if(!userEntity) {
        throw new Error("userEntity is null");
    }
    
    print(userEntity);
}

the return type from findOne is

(Document<any, any, User> & User & { _id: Types.ObjectId; }) 

that seems very verbose for putting in the function signature each time I want to reference it.

I also could not find a utility type build into the type definitions. Should we create our own type to wrap this up

type DocDef<T> = (Document<any, any, T> & T & { _id: Types.ObjectId; });

or add _id to the User interface?

I am wondering what is the best practice?

Also curious what DocumentDefinition is supposed to be used for?

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