Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Missing TypeScript type definition for "pre and post middleware remove '' method #13518

Closed
2 tasks done
khantopa opened this issue Jun 16, 2023 · 5 comments · Fixed by #13683
Closed
2 tasks done

Missing TypeScript type definition for "pre and post middleware remove '' method #13518

khantopa opened this issue Jun 16, 2023 · 5 comments · Fixed by #13683
Labels
docs This issue is due to a mistake or omission in the mongoosejs.com documentation typescript Types or Types-test related issue / Pull Request
Milestone

Comments

@khantopa
Copy link

Prerequisites

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

Mongoose version

7.1.0

Node.js version

20.3.0

MongoDB server version

6.0.6

Typescript version (if applicable)

5.0.4

Description

I have noticed that there is a missing TypeScript type definition for the 'pre middleware remove' method in Mongoose.
It show's this error

 The last overload gave the following error.
  Argument of type '"remove"' is not assignable to parameter of type 'RegExp | "insertMany"'.

Eg:

import mongoose from 'mongoose';

interface IMyType {
  name: string;
}

interface IMyTypeModel extends mongoose.Model<IMySchema> {}

const mySchema = new mongoose.Schema<IMySchema, IMySchemaModel>(
  {
    name: {
      type: String,
    },
  },
);

mySchema.pre('remove', async function (next) {
  console.log(this)
  next();
});

Steps to Reproduce

  1. Set up a TypeScript project with the necessary dependencies, including Mongoose.
  2. Create a schema definition file (e.g., mySchema.ts) for your Mongoose schema.
  3. Inside the schema definition file, import the required dependencies, including the Mongoose library and any other relevant modules.
  4. Define your schema using the mongoose.Schema function, specifying the necessary properties, fields, and options.
  5. Register a pre middleware for the 'remove' hook by using the pre method on the schema instance.
  6. In the pre method, pass 'remove' as the first argument to target the removal operation.
  7. Define an anonymous async function as the second argument to execute the middleware logic before the removal operation.
  8. Save the schema and export it from the file.
  9. In another TypeScript file (e.g., index.ts), import the schema definition from the previous step.
  10. Use the schema to create an instance or model based on the defined schema.
  11. Perform a removal operation on an instance or model, such as calling the remove or deleteOne method.
  12. Observe that TypeScript does not provide proper type checking or intellisense for the pre middleware remove method, indicating the missing type definition issue.

By following these steps, you should be able to reproduce the problem of the missing TypeScript type definition for the pre middleware remove method in Mongoose.

import mongoose from 'mongoose';

interface IMyType {
  name: string;
}

interface IMyTypeModel extends mongoose.Model<IMySchema> {}

const mySchema = new mongoose.Schema<IMySchema, IMySchemaModel>(
  {
    name: {
      type: String,
      required: [true, 'Name is required.'],
      trim: true,
    },
  },
);

mySchema.pre('remove', async function (next) {
  console.log(this)
  next();
});

Expected Behavior

  1. The TypeScript compiler should recognize and provide type checking for the pre method and its arguments, including the remove hook.
  2. The TypeScript compiler should infer and enforce the correct types for the anonymous async function passed as the second argument to the pre method.
  3. Intellisense and autocompletion should be available within the async function, suggesting the appropriate properties and methods of the schema or document being removed.
  4. If any incorrect types or incompatible operations are performed within the async function, TypeScript should generate appropriate type error messages during compilation.
  5. The Mongoose runtime should properly invoke the pre middleware function before the removal operation takes place, allowing for any necessary pre-removal logic to execute.
  6. The async function should have access to the correct context and variables related to the removal operation.
  7. The async function should be able to modify the document being removed or perform additional asynchronous operations before the actual removal occurs.
  8. If the async function returns a Promise, Mongoose should correctly handle the resolution of the Promise, ensuring that the removal operation is executed after the asynchronous tasks in the async function have completed.
khantopa added a commit to khantopa/mongoose that referenced this issue Jun 16, 2023
@khantopa khantopa changed the title Missing TypeScript type definition for 'pre middleware remove' method Missing TypeScript type definition for "pre and post middleware remove '' method Jun 16, 2023
@khantopa
Copy link
Author

I apologize for not realizing that the 'remove' method is deprecated in the current version.

@vkarpov15 vkarpov15 reopened this Jun 18, 2023
@vkarpov15 vkarpov15 added this to the 7.3.2 milestone Jun 18, 2023
@vkarpov15 vkarpov15 added the typescript Types or Types-test related issue / Pull Request label Jun 18, 2023
@vkarpov15
Copy link
Collaborator

Yeah remove() was deprecated in a previous version, and removed in Mongoose 7. So this is expected.

@vkarpov15 vkarpov15 removed this from the 7.3.2 milestone Jun 20, 2023
@mrdulin
Copy link

mrdulin commented Jul 14, 2023

@vkarpov15 Should the remove middleware examples in documentation be updated?

schema.post('remove', function(doc) {
  console.log('%s has been removed', doc._id);
});

When use it with TS, TSC will throw an error:

o overload matches this call.
  The last overload gave the following error.
    Argument of type '"remove"' is not assignable to parameter of type 'RegExp | "insertMany"'.ts(2769)

@vkarpov15 vkarpov15 reopened this Jul 17, 2023
@vkarpov15 vkarpov15 added this to the 7.4.2 milestone Jul 17, 2023
@vkarpov15 vkarpov15 added the needs repro script Maybe a bug, but no repro script. The issue reporter should create a script that demos the issue label Jul 17, 2023
@vkarpov15
Copy link
Collaborator

@mrdulin nope, that documentation looks correct. Might be a TypeScript issue, will have to check

@IslandRhythms IslandRhythms added confirmed-bug We've confirmed this is a bug in Mongoose and will fix it. and removed needs repro script Maybe a bug, but no repro script. The issue reporter should create a script that demos the issue labels Jul 19, 2023
@IslandRhythms
Copy link
Collaborator

Am able to get same error message

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

// 1. Create an interface representing a document in MongoDB.
interface IUser {
  name: string;
  email: string;
  avatar?: string;
}

// 2. Create a Schema corresponding to the document interface.
const userSchema = new Schema<IUser>({
  name: { type: String, required: true },
  email: { type: String, required: true },
  avatar: String
});

userSchema.pre('remove', function(doc) {
  console.log('the doc', doc);
});

// 3. Create a Model.
const User = model<IUser>('User', userSchema);

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

async function run() {
  // 4. Connect to MongoDB
  await connect('mongodb://127.0.0.1:27017/test');

  const user = new User({
    name: 'Bill',
    email: 'bill@initech.com',
    avatar: 'https://i.imgur.com/dM7Thhn.png'
  });
  await user.save();

  console.log(user.email); // 'bill@initech.com'
}

@vkarpov15 vkarpov15 added docs This issue is due to a mistake or omission in the mongoosejs.com documentation and removed confirmed-bug We've confirmed this is a bug in Mongoose and will fix it. labels Aug 1, 2023
vkarpov15 added a commit that referenced this issue Aug 1, 2023
docs(middleware): fix old example using `post('remove')`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs This issue is due to a mistake or omission in the mongoosejs.com documentation typescript Types or Types-test related issue / Pull Request
Projects
None yet
4 participants