Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.94k stars 3.84k forks source link

Conflict between doc example and type declaration for query middleware #10531

Closed mark-night closed 3 years ago

mark-night commented 3 years ago

Do you want to request a feature or report a bug? Not sure. Read below. What is the current behavior? Doc example reads this.model in query middleware (https://mongoosejs.com/docs/middleware.html#notes),

schema.pre('findOneAndUpdate', async function() {
  const docToUpdate = await this.model.findOne(this.getQuery());
  console.log(docToUpdate); // The document that `findOneAndUpdate()` will modify
});

This does work in practice. However, in typescript, this raises error indicating 'Property "model" not exist in Query...' (with this specified as type Query<any, any> ) The example is somewhat confusing though because query does has findOne method, what is the point reading this.model?

If the current behavior is a bug, please provide the steps to reproduce. Not sure if this is a spot needs to be updated in doc example or something missed in type declaration.

What is the expected behavior?

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version. Node v12.22.1 Mongoose v5.13.3

vkarpov15 commented 3 years ago

Query instances have a model property, but looks like that's missing from our TypeScript bindings. Will fix :+1:

vkarpov15 commented 3 years ago

If you do this.findOne() in query middleware, you're switching the current query to findOne, not executing a separate query. You should do this.model.findOne() to create a new query instance.

mark-night commented 3 years ago

If you do this.findOne() in query middleware, you're switching the current query to findOne, not executing a separate query. You should do this.model.findOne() to create a new query instance.

That's a good hint, never thought that way. It now makes sense clearly! Thanks.