Hello, I am brand new to exploring stack overflow and the world of development. I have been self-teaching myself how to code using React and Express, so please forgive me if my question seems basic or implausible. I still have many fundamental gaps in my knowledge! :)
Currently, I am working with a MongoDB database that contains over 25 collections (and likely more in the future). Each collection has a unique schema defined in mongoose.
Below are the Express API endpoints for each collection:
- https://localhost:5030/mySchema/...
- https://localhost:5030/myShema2/... -.... etc
I am in the process of refactoring my code to remove the control and route logic. Previously, I had the logic appended after the verb in the route path, which worked but was messy, cumbersome, and limiting. Therefore, I am separating out the controller logic now.
Each collection/API endpoint has common URLs and API functions applied to them:
- getAll
- findByName
- summary (filtering out unwanted attributes)
- etc
In the example code provided below:
const mySchema = require('../models/mySchema') // Sample import
const getAll = (req, res) => {
console.log('Request made to fetch assets data')
try {
mySchema.find()
then((resultsFound) => res.json(resultsFound))
console.log('Results Found are', resultsFound)
} catch (error) {
next(err) //Built-in Express error handling
}
}
Is there a way to make the schema name dynamic so this controller code can be reused across different schema definitions like mySchema, mySchema1, mySchema2, etc.?
So far, I have only attempted manual templating of the configuration.
One hacky solution I thought of is extracting the suffix from the URL request and setting it as a variable. However, this solution is limited and only works when the schema definition is in the same place in the URL.
Are there any more extensible ways, using techniques that I may not be familiar with and might struggle to understand, to achieve dynamic schema attribution in a controller?