Tips for creating a concise switch statement in JavaScript, incorporating both the use of Express and Mongoose

Here's the current situation:

I am tasked with searching in 3 different databases for an ID associated with a shift. Each shift is classified as either an Activity, Food and Beverages, or Other type.

When making the search, the type is provided in the request body.

To handle this, I am using a switch statement to determine which database to search through.

switch(type_shift){
     case("activity"):
     response = await ActivityShiftDB.findByIdAndUpdate(id_shift, {$pull : {"support": user}}).exec();
     break;

     case("fandb"):
     response = await FoodBeveragesShiftDB.findByIdAndUpdate(id_shift, {$pull : {"support": user}}).exec();
     break;

     case("other"):
     response = await OtherShiftDB.findByIdAndUpdate(id_shift, {$pull : {"support": user}}).exec();
     break;
   }

However, I feel like this code is not very DRY (Don't Repeat Yourself). Is there a better approach to handling this situation?

Answer №1

Rearrange the code structure to improve readability:

let shiftDB;
switch (type_shift) {
    case "activity":
        shiftDB = ActivityShiftDB;
        break;
    case "fandb":
        shiftDB = FoodBeveragesShiftDB;
        break;
    case "other":
        shiftDB = OtherShiftDB;
        break;
    default:
        throw new Error("unknown type_shift");
}
response = await shiftDB.findByIdAndUpdate(id_shift, {$pull : {"support": user}}).exec();

Consider a more concise approach without using a switch statement:

const shiftDBsByType = {
    "activity": ActivityShiftDB,
    "fandb": FoodBeveragesShiftDB,
    "other": OtherShiftDB,
}
if (!(type_shift in shiftDBsByType)) {
    throw new Error("unknown type_shift");
}
response = await shiftDBsByType[type_shift].findByIdAndUpdate(id_shift, {$pull : {"support": user}}).exec();

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

Prevent user input in Vue.js until the value has been modified

Need help handling initial input values: <input type="text" v-model="name" ref="input" /> <button type="submit" :disabled="$refs.input.defaultValue == $refs.input.value">Submit</button> Encountering an error with the disabled binding: C ...

What sets Import apart from require in TypeScript?

I've been grappling with the nuances between import and require when it comes to using classes/modules from other files. The confusion arises when I try to use require('./config.json') and it works, but import config from './config.json ...

The Response body was abruptly cut off due to an unexpected JSON input error, which falls under the category of self

Upon trying to access the content of a successful HTTP POST request's body in a Response, I encounter the following error: SyntaxError: Unexpected end of JSON input. Here is the Express.js code snippet I used to send the response: res.status(204).sen ...

A see-through object appears only properly when viewed from one specific angle

I am currently working with THREE.js and the WebGL renderer, facing an issue with a self-transparent object in my scene. This object is composed of a single geometry with a basic material that includes a texture and has the transparent: true property enabl ...

ReactJS: Dealing with issues in setting a dynamic index for the setState key

I have been attempting to utilize setState within a for loop using index in the following manner: for (var i = 0; i <= 9; i++) { this.setState({ location_option[i]: resourceData.location_option+i, location_option[i]_type: resourceData.locatio ...

Discovering ways to align specific attributes of objects or target specific components within arrays

I am trying to compare objects with specific properties or arrays with certain elements using the following code snippet: However, I encountered a compilation error. Can anyone help me troubleshoot this issue? type Pos = [number, number] type STAR = &quo ...

Guide to modifying the class color using javascript

I am experiencing an issue with this particular code. I have successfully used getElementById, but when I try to use document.getElementsByClassName("hearts");, it does not work as expected. This is a snippet of my HTML code: status = 1; function change ...

Collapse an array containing objects with nested objects inside

Similar questions can be found here and here, but I am struggling to modify the code provided in the answers to fit my specific needs due to its conciseness. The structure of my array of objects is as follows: [ { id: 1, someProp: &quo ...

Using Sinonjs fakeserver to handle numerous ajax requests

I utilize QUnit in combination with sinon. Is there a way to make sinon's fakeserver respond to multiple chained ajax calls triggered from the same method? module('demo', { beforeEach: function(){ this.server = sinon.fakeServer. ...

How can I incorporate dynamic data to draw and showcase graphs on my website using PHP?

I am currently working on a project that requires displaying a graph showing the profit of users per day. Currently, I have implemented code to display a static graph on my page. <script type="text/javascript" src="https://www.google.com/jsapi">< ...

Adjust the overall size of the CSS baseball field

Attempting to adjust the size of the baseball field proved challenging, as it wasn't a simple task. Is there a way to achieve this effectively? Thanks, HTML - is using DIV the only method for resizing? I couldn't find a way to resize everything a ...

When a project sets useBuiltIns to 'usage', there is an issue with importing the library generated by Webpack

I am eager to create a versatile UI component library and bundle it with Webpack. However, I encountered an issue when trying to import it into another project that has useBuiltIns: 'usage' specified in the babelrc file. The import fails with the ...

RS256 requires that the secretOrPrivateKey is an asymmetric key

Utilizing the jsonwebtoken library to create a bearer token. Following the guidelines from the official documentation, my implementation code appears as below: var privateKey = fs.readFileSync('src\\private.key'); //returns Buffer let ...

Two users are attempting to book two different appointments at the same time in Node.js utilizing MongoDB. However, only one user will

Within the functionality of my application, users have the ability to reserve a booking for time XYZ, as long as that specific time slot is still available. However, imagine if another user is also trying to book time XYZ simultaneously with the first us ...

Exploring the Possibilities: Incorporating xlsx Files in Angular 5

Is there a way to read just the first three records from an xlsx file without causing the browser to crash? I need assistance with finding a solution that allows me to achieve this without storing all the data in memory during the parsing process. P.S: I ...

Running SOAP services with Jasmine framework in Node.js: A step-by-step guide

I've been successfully using the jasmine-node framework for automating my API tests. I can easily run REST services and retrieve results using node-fetch or http modules. However, my project also requires testing SOAP services. Can anyone provide guid ...

Creating a form in PHP with the power of JavaScript, AJAX, and jQuery

I have successfully created a registration form using HTML, processed the data with PHP, and utilized javascript, ajax, and jquery. However, I am facing an issue where I want to display a notification stating whether the operation was "inserted/failed" on ...

Button react-native press following textInput within scroll view aware of keyboard movements

I'm currently facing an issue where I have a TextInput and a button nested inside a KeyboardAwareScrollView. The goal is for the user to input some text and then tap the button created using TouchableOpacity, which should send the inputted text forwar ...

Getting information from a JSON file with several variables: A guide for using node.js, express, and jQuery

In order to minimize the number of Ajax calls, I am attempting to send three variables in a single Ajax response. However, I am facing difficulties when trying to process the data on the client side. Let me elaborate on my issue and if sending multiple var ...

Obtain information from local server in a React Native application

I am attempting to retrieve data from my localhost using React Native. My database, named "test," was created using MySQL. The table within the database is named "users" and contains the following rows: picture The connections are established in the ...