How can I override the typeof mongoose Model methods in typescript

  • Hello, everyone I’m trying to write a history log for DB modification like edit, delete, find, etc… and also i want to define which user is done this modifications so the user data is saved in res.locals.user and i wrote a function that will act like a middleware between the method call and DB query so for example
const { Document, Model, default: mongoose } = require('mongoose');
//store reference to original 
const findOriginalMethod = Model.find;

// override the mongoose methods to accept response as the first parameter
UsersSchema.statics.find = async function (res,...args) {
  let self = this;
  const result = await findOriginalMethod.call(self, ...args);
  const historyData = {
    user: res.locals.user.userName,
    userId: res.locals.user._id,
    action: 'find',
    collectionName: 'Users',
  };


   historyData.data = result;
   historyData.documentId = result._id;
   // historyEmitter.emit('saveLog', historyData);

  return result;
}
  • the function above works fine in JS but when trying to define types by typescript I couldn’t achieve that i tried extend the model types by something like the following
import express from 'express';
import { Document, Model, default as mongoose } from 'mongoose';

//store reference to original 
const findOriginalMethod = Model.find;
//get the return type of the accessed method  
type findReturnType = ReturnType<typeof findOriginalMethod>;
//get the type parameters of the accessed method  
type findParamsType = Parameters<typeof findOriginalMethod>;

// override the mongoose methods to accept response as the first parameter
UsersSchema.statics.find = async function (res: express.Response, ...args: findParamsType): Promise<findReturnType> {
  let self = this;
  const result = await findOriginalMethod.call(self, ...args) as any;
  const historyData: any = {
    user: res.locals.user.userName,
    userId: res.locals.user._id,
    // db: res.locals.db,
    source: res.locals.payload.role,
    action: 'find',
    collectionName: 'Users',
  };

  historyData.data = result;
  historyData.documentId = result._id;

  return result;
}


export interface IUserMethods extends Model<IUser> {
  findByCredentials(options: findByCredentialsItems): Promise<IUser>;
  find(res: express.Response, ...args: findParamsType): Promise<findReturnType>;
}


// const Users = connection.model('Users') || connection.model('Users', UsersSchema);
const Users = connection.models.Users
  ? connection.model<IUser, IUserMethods>('Users')
  : connection.model<IUser, IUserMethods>(
    'Users',
    UsersSchema,
  );


export default Users;
  • In example above tried to define the typeof find method to IUserMethods interface but got the following error
Interface 'IUserMethods' incorrectly extends interface 'Model<IUser, {}, {}, {}, Document<unknown, {}, IUser> & IUser & { _id: ObjectId; }, any>'.
  The types returned by 'find(...)' are incompatible between these types.
    Type 'Promise<Query<unknown[], unknown, {}, any, "find">>' is missing the following properties from type 'Query<(FlattenMaps<IUser> & { _id: ObjectId; })[], any, {}, IUser, "find">': _mongooseOptions, exec, $where, all, and 86 more.
  • Also I tried to override the typeof find method globally by global.d.ts but it’s also doesn’t work
import mongoose from "mongoose";
import express from 'express';

declare global {
  namespace mongoose {
    interface Model<T> {
      find(res: express.Response, ...args: Parameters<typeof mongoose.Model.find>): Promise<ReturnType<typeof mongoose.Model.find>>
    }
  }
}

  • Can anyone help me to override the typeof original mongoose model methods to aceept response as the first parameter then the other parameters next ?

New contributor

Shadow Fighter is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật