How to write a generic function to resolve PopulatedDoc type variables? #15121
Open
Description
Prerequisites
- I have written a descriptive issue title
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:
// Check if 'myPopulatedDocProp' has already been populated in a previous part of the code
if (myDocument.myPopulatedDocProp instanceof AnotherModel) {
return myDocument.myPopulatedDocProp;
}
// If 'myPopulatedDocProp' was not populated, perform a database query to find and populate the document property
const result = await AnotherModel
.findById(myDocument.myPopulatedDocProp) // Query the AnotherModel to find the document by ID
.orFail(); // Throw an error if the document is not found
return result; // 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:
export const findOrReturnInstance = async <T extends Document>(
populatedDoc: PopulatedDoc<T>,
model: Model<T>,
) => {
if (populatedDoc instanceof model) {
return populatedDoc;
}
const result = await model
.findById(populatedDoc)
.orFail();
return result;
};
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. 🙏🏻