Skip to content

There is a bug in the automatic inference of the ts type for methods #15869

@dadajiege123

Description

@dadajiege123

Prerequisites

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

Mongoose version

9.0.0

Node.js version

14.x

MongoDB server version

8.0.5

Typescript version (if applicable)

5.9.3

Description

跟文档说的不一样,static定义的方法可以自己推断, methods的不行,可以修复吗

Steps to Reproduce

const wxmpUserSchema = new Schema({
    openid: { type: String, required: true, index: true, unique: true }, //必须要
    phoneNumber: { type: String, required: true, index: true, unique: true }, //必须要
    nickName: { type: String, required: true, default: '默认用户' },
    avatarImage: { type: Schema.Types.ObjectId, ref: 'uploadFile' },
    roles: [{ type: Schema.Types.ObjectId, ref: 'frontRole' }],
    createTime: Date,
    loginTime: Date,
    //陪玩专属字段
    gamer_balance: { type: Number, default: 0 }, //陪玩余额,元为单位
    gamer_phoneNumber: { type: String, default: '' }, //陪玩联系手机号
    gamer_introduction: { type: String, default: '' }, //陪玩个人介绍, 不大于200个字
    gamer_gamerLevel: { type: Schema.Types.ObjectId, ref: 'gamerLevel' },
    gamer_imageAndVideoList: [{ type: Schema.Types.ObjectId, ref: 'uploadFile' }], //陪玩展示的图片和视频列表
    gamer_status: { type: String, default: '离线' }, //是否在线
    gamer_completedOrderCount: { type: Number, default: 0 }, //已完成的单数
    gamer_currentWeekCompleteOrderCount: { type: Number, default: 0 }, //当前一周完成的单数
    gamer_currentWeeklyEndTime: { type: Date, default: null }, //本周开始时间
    gamer_nextWeekendTime: { type: Date, default: null }, //下周结算时间
}, {
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
    virtuals: {
        permissions: {
            get(this: any) {
                if (!this.roles) return [];

                // 扁平化合并所有角色的 permissions
                return this.roles
                    .flatMap((role: any) => role.permissions)
                    .filter((perm: any) => perm); // 过滤空值
            }
        },
        gamer_pricePerHour: {
            get(this: any) {
                if (!this.gamer_gamerLevel) return 100;
                return this.gamer_gamerLevel.pricePerHour;
            }
        }
    },
    methods: {
        hasPermission(permission: string) {
            // 注意:这里不能用箭头函数!必须用普通 function 以保留 this 指向文档实例
            // 获取虚拟字段 permissions(会自动触发 getter)
            const perms = (this as any).permissions; // 这里会调用你定义的 virtuals.permissions.get
            if (!Array.isArray(perms)) return false;
            return perms.includes(permission);
        }
    },
    statics: {
        async fuzzySearch(options: {
            currentPage: number,
            pageSize: number,
            search?: 'phoneNumber' | 'nickName',
            keyword?: string,
            roleIds?: string[],
            projections?:Projection<WxmpUserDoc>,
        }) {
            let { currentPage, pageSize, search, keyword, roleIds, projections } = options;
            //搜索query
            let filter: { phoneNumber?: RegExp, nickName?: RegExp, roles?: {$in:string[]} } = {}
            //userId开头匹配
            if (search && keyword) {
                filter = { [search]: new RegExp(`^${escapeRegExp(keyword.trim())}`, 'i') };
            }
            if (roleIds && roleIds.length !== 0) {
                filter.roles = { $in: roleIds }
            }
            let frontUserList = await this.find(filter, projections)
                .skip((currentPage - 1) * pageSize)
                .limit(pageSize)
                .populate('avatarImage')
                .populate('roles')
                .populate('gamer_imageAndVideoList')
                .populate('gamer_gamerLevel');

            let total = await this.countDocuments(filter) as number;

            return { frontUserList, total }

        }
    }
});

const WxmpUser_Model = mongoose.model('wxmpUser', wxmpUserSchema);


export default WxmpUser_Model

Expected Behavior

hasPermission的类型没有出现

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.typescriptTypes or Types-test related issue / Pull Request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions