How can I define a schema attribute for a controller in Express JavaScript?

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?

Answer №1

My suggestion is to consider restructuring the code architecture by assigning each route its own controller, tailored to work with the appropriate schema model.

This approach will simplify future tasks involving database queries or other operations with the schema model.

I understand the intention behind using a single controller for all getAll routes, but I am uncertain if it offers the best solution.

Furthermore, I recommend exploring the repository pattern and adhering to node.js best practices for code architecture, including segregating routes and controllers. For more insights, refer to this resource.

Answer №2

Begin by creating a schema without any initial configuration, exporting all of it in a single file, and then proceed with the configuration steps

const { model } = require('mongoose');
const mySchema = require('../models/mySchema')
const mySchema1 = require('../models/mySchema1')
const mySchema2 = require('../models/mySchema2')
const mySchema3 = require('../models/mySchema3')
const mySchema4 = require('../models/mySchema4')


export default allModels = {
    modelName: model("modelName", mySchema),
    modelName: model("modelName", mySchema1),
    modelName: model("modelName", mySchema2),
    modelName: model("modelName", mySchema3),
    modelName: model("modelName", mySchema4),
}

To import, you can use one of the following methods

import model.myschema1 from './path of those models' || 
import model.myschema1 as myschema1 from './path of those models'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fetch the count of files in a directory using AJAX

I'm attempting to fetch the number of files in a folder and compare it with the maxfiles value. Within dropzone.js, there is a function that looks like this: Dropzone.prototype._updateMaxFilesReachedClass = function() { if ((this.options.maxF ...

When attempting to execute a function within another function in JavaScript, a ReferenceError is triggered

I recently developed a straightforward app that utilizes the Google Drawing Library (https://developers.google.com/maps/documentation/javascript/examples/drawing-tools) to allow users to draw circles on a map. The first circle represents the source locatio ...

Display various items using only one EJS scriptlet tag

I'm currently facing a challenge with rendering two objects using EJS. I am curious to know if it is feasible to render them both within the same pair of scriptlet tags or if they need to be rendered separately? So far, I have been able to successful ...

Unlocking the potential of Object[value] in JavaScript/jQuery: A guide to extracting its value

I have a table named 'mytable' with the following structure: <tr> <td><input type="checkbox" name="check[]" value="11"></td> <td>11</td> <td>2014-11-06 18:49:26</td> < ...

What is the best way to show the user's name on every page of my website?

I'm facing an issue where I can successfully capture the username on the home page using ejs after a login, but when transitioning to other pages from the home page, the username is no longer visible. It seems like I am missing some logic on how to ha ...

How can I make a website enable text selection?

After purchasing access to a language learning website, I was disappointed to discover that I couldn't even select text on the pages. It appears they offer an "upgrade" option for users to download lesson texts, and it seems like the ability to selec ...

Using jQuery to dynamically populate a list with the information from a JSON dataset

How can I utilize JSON data to ensure that jquery populates the correct ul in this code snippet, creating 5 ul and populating them with li elements? Expected output: The slides should be assigned to specific modules as indicated in the JSON data, instead ...

Are You Able to Develop a Floating Window That Stays Persistent in JavaScript?

Looking to create a persistent floating window in a NextJS 14 app. This window needs to remain on top, even when navigating between browser windows. Want it to stay visible even when the browser window is minimized, like a Picture-In-Picture feature. Mos ...

Attempting to upload an item using ThreeJs

Can someone assist me with loading an object file from my local browser in Threejs ( Rev 71)? I keep encountering an error that says loadModel.html:1 Uncaught SyntaxError: Unexpected token #. Even after trying to load the object file using chrome --allow- ...

Chess.js TypeScript declaration file for easy implementation

Currently, I am delving into learning typescript and have taken up the challenge of crafting a declaration file for the chess.js library. However, it seems that I am struggling to grasp the concept of creating one. Whenever I attempt to import the library ...

I am unable to halt the relentless stream of asynchronous events

Struggling to retrieve an array using a loop in the asynchronous environment of nodejs. Check out my code below: getDevices(userIDs, function(result) { if (result) { sendNotification(messageUser, messageText, result); res.send("Success"); } else { ...

Troubleshooting drag-and-drop functionality in a JavaScript HTML5 application resembling a Gmail upload interface

Here is a snapshot of my user interface: Each node in the tree structure is represented by an <li> element along with an <a> link. Furthermore, each folder serves as a dropzone for file uploads similar to the drag-and-drop feature found in Gm ...

Obtain a controller's reference from a callback by utilizing TypeScript

Implementing a simple controller that utilizes a directive/component and passes a function as binding. However, when the function is called, there is no reference available to access any of the controller class services. Within the "public onTileClicked" ...

How can we eliminate duplicate arrays of objects within a multi-dimensional array using ReactJS and JavaScript?

let galleryItems = [ {id: 1029, name: 'College-Annual-Day.jpg', ext: 'jpg', mime: 'image/jpeg', size: 91153, …}, {id: 1029, name: 'College-Annual-Day.jpg', ext: 'jpg', mime: 'image/jpeg', si ...

What is the process for integrating php script within javascript?

Is it possible to incorporate php scripts into javascript[1] in the same manner as it can be done in html[2]? server.php: <?php echo 'hello World'; ?> client.js (or client.php if needed): function foo() { var i = <?php include ...

JavaScript functioning exclusively for specific list items within an unordered list

After implementing JavaScript on my website, I noticed that it only works when clicking on certain list items (li's) and not on others. Specifically, the functionalities for Specialties, Contact Us, and Referral Schemes are not working correctly. ...

Exploring the depths of Mongoose queries with recursive parent references

I'm attempting to replicate the functionality of this MongoDB example using Mongoose, but it seems more complicated in Mongoose. Am I trying to force a square peg into a round hole? This source is taken from http://www.codeproject.com/Articles/521713 ...

How can you determine the class of an element that was clicked within an iframe?

Is it possible to retrieve the class of an element that is clicked within an iframe? Here is the HTML code: <input id="tag" type="text"> <iframe id="framer" src="SameDomainSamePort.html"></iframe> This is the JavaScript code: $(docum ...

Personalizing the pop-up window using window.open

When clicking a hyperlink on a page, I need to open multiple pop-up windows. To achieve this, I must use the Window.open function instead of showModalDialog. However, I have noticed that the appearance is not satisfactory when using Window.open. (Essentia ...

Discovering additional element information while utilizing the 'Sortable' feature

My Current Objective: In my setup, I have a 'calendar' comprising 5 columns, each column containing 5 separate divs known as timeslots. The main purpose here is to show appointments in these specific timeslots and utilize JQuery's Sortable ...