francescov1 / mongoose-tsgen

A plug-n-play Typescript generator for Mongoose.
105 stars 25 forks source link

Promise / Query conflict #53

Closed www-chique closed 3 years ago

www-chique commented 3 years ago

I am sorry if this is not related to your package. However, I tried a little searching and couldn't determine from where this problem is originating. However, this problem started after I updated mongoose-tsgen to v8, and subsequently the mongoose version as well to the latest, along with it's types, as you suggested.

The main culprit lines of code are the follows. I am using await-to-js to simply wrap the Queries so I can catch the error inline without having to do try/catch always.

const [err, dbUser] = await to(
     User.findOne({ email: this.email, deleted: false }).select(userRequiredFields).lean()
);

But this User.findOne returns a Query type, which is conflicting with the async await's expected "Promise" type.

I'll attach some screenshots.

  1. Here I am showing a simple Query to demonstrate the return type of this function. image

  2. Here is the return type that comes up when I use "await" in front. It shows the correct type. image

  3. But the moment I wrap it around "to" function, it shows a type mismatch. image

Well it could be an issue with this await-to-js, but given it's so popular, I thought I am doing something wrong. Maybe you can again point me to the right direction. If it is not in the scope of this tool, you may close this. I will try to find a solution somehow.

Many thanks again!

Steps to Reproduce:

  1. Use await-to-js
  2. Wrap a simple mongoose query with the await-to-js' "To" function (as my example code)
  3. Notice the Query and Promise types mismatching
francescov1 commented 3 years ago

Hey @www-chique, thanks for submitting the issue!

I believe the problem with the code above is that you are missing an exec() call at the end of your queries. I think you are just running into this issue with the update to mongoose-tsgen v8 because this update came with stronger/better typing for queries, so before the issue may not have been caught by typescript previously.

See Mongoose docs on promises for more info and let me know if this solves the issue!

www-chique commented 3 years ago

Alright, using the "exec" fixed the problem. Thanks a lot, you're the best. Works perfect now, and also updated to v8. I'm pretty excited :)

francescov1 commented 3 years ago

Awesome to hear! Check out the new update to 8.2.2 if you have a chance, it adds support for much better population typing! Would love to hear any feedback 🥳