Home > Net >  Typescript error when converting js to typescript in express js model
Typescript error when converting js to typescript in express js model

Time:06-30

I am moving my express.js code to typescript. Here is a simplified version of my user model.

//user.model.ts
import { Schema, Types } from 'mongoose';

export interface User {
  name: string;
  active: boolean;
}

const UserSchema = new Schema<User>(
  {
    name: {
      type: String,
      required: [true, 'First Name is required'],
      trim: true,
    },
    active: {
      type: Boolean,
      deafult: true,
      select: false,
    },
  },
  {
    timestamps: true,
  }
);


UserSchema.pre(/^find/, async function (next) {
  this.find({ active: { $ne: false } });
  next();
});

const User = mongoose.model('User', UserSchema);

export default User;

Two questions here:

  1. Do I need to include timestamp in my interface? It's not showing any error as such, but I am not sure if timestamps will be added correctly to hydrated documents

  2. My pre hook shows this error: Property 'find' does not exist on type 'Document<unknown, any, User> & User & { _id: ObjectId; }'.ts(2339)

I am not sure how to resolve error number 2. Any pointers are appreciated.

CodePudding user response:

The issue is caused by using a regular expression to match the hook:

UserSchema.pre(/^find/, async function (next) { … })

Because a regular expression can, in theory, match anything, TypeScript isn't able to infer the type of middleware (document or query).

To solve this, use an array containing each hook you want to apply the middleware to:

UserSchema.pre([ 'find', 'findOne', 'findOneAndUpdate' ], function (next) {
  this.find({ active: { $ne: false } });
  next();
});
  • Related