You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In my project, I often find myself having to implement this code:
// Check if 'myPopulatedDocProp' has already been populated in a previous part of the codeif(myDocument.myPopulatedDocPropinstanceofAnotherModel){returnmyDocument.myPopulatedDocProp;}// If 'myPopulatedDocProp' was not populated, perform a database query to find and populate the document propertyconstresult=awaitAnotherModel.findById(myDocument.myPopulatedDocProp)// Query the AnotherModel to find the document by ID.orFail();// Throw an error if the document is not foundreturnresult;// Return the populated document property
Is it possible to write a generic function so that I don't have to rewrite the same exact code but with different models?
I tried with this code but it doesn't work:
Is it the right approach or am I doing something wrong?
Attention, with this generic function I want to ensure that any virtual variables and instance methods, etc., are preserved.
Thank you for your help. 🙏🏻
The text was updated successfully, but these errors were encountered:
The approach is reasonable, you just need to type model correctly. I would also recommend against using PopulatedDoc<> type for reasons explained here.
Take a look at the following script, would this approach work for you?
Prerequisites
Mongoose version
8.9.1
Node.js version
20.10.0
MongoDB version
6.0.2
Operating system
macOS
Operating system version (i.e. 20.04, 11.3, 10)
No response
Issue
In my project, I often find myself having to implement this code:
Is it possible to write a generic function so that I don't have to rewrite the same exact code but with different models?
I tried with this code but it doesn't work:
Is it the right approach or am I doing something wrong?
Attention, with this generic function I want to ensure that any virtual variables and instance methods, etc., are preserved.
Thank you for your help. 🙏🏻
The text was updated successfully, but these errors were encountered: