Create a more concise JavaScript function for updating MongoDB using if/else statements

Can this function be optimized for efficiency and readability? I'm not a fan of the repetitive if/else structure, especially considering that it's only setting 'status.edited': false when method equals 'reset'. Otherwise, it stays unmodified.

function optimizeUpdate(id, method) {
    var timestamp = new Date().getTime();

    Collection.update(
        { _id: id }, 
        { 
            $set:   { 'status.version': timestamp },
            $unset: { 'status.editing': '' }
        }
    );

    if (method === 'reset') {
        Collection.update(
            { _id: id }, 
            { 
                $set:   { 'status.edited': false }
            }
        );
    }

}

Answer №1

To dynamically construct your query, follow the example below:

function modifyData(id, action) {
    var timestamp = new Date().getTime();
    var updateQuery = { 
        '$set': { 'data.timestamp': timestamp },
        '$unset': { 'data.editing': '' } 
    };

    if (action === 'reset')
        updateQuery['$set']['data.edited'] = false;

    Database.update( { '_id': id }, updateQuery );
}

Answer №2

Generate a custom object containing dynamic properties and then provide it as an input to the query.

var customObj = {
    'status.version': currentTimestamp
};

if(action === 'reset') {
    customObj['status.edited'] = false;
}

Collection.update({
    _id: documentId
}, {
    $set: customObj,
    $unset: {
        'status.editing': ''
    }
});

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

How can I change the displayed value of a 'select' element programmatically in Internet Explorer?

My interactive graphic has a drop-down menu implemented with a <select> element. Everything functions correctly, except when using Internet Explorer. The issue arises when attempting to programmatically change the selected value of the <select> ...

Utilizing AJAX for seamless communication between JavaScript and PHP within a modal dialogue box

I'm struggling with learning how to effectively use ajax. In the project I'm currently working on, I have a chart where I can select different people. Once I click on a person's button, their information gets updated in the database. However ...

Organize JSON data in Angular 6 from an observable based on a specific key

Note: While I am familiar with sorting a regular array of objects using .sort(), I am facing a challenge with an observable object that I am not accustomed to. My task involves retrieving a JSON array of objects with a service: import { Injectable } from ...

Failed attempt to perform Ajax requests for REST API data

I am currently working on developing an application that requires a login through a REST API to retrieve a session id. To achieve this, I have set up a button that triggers a JavaScript function for making an AJAX call to authenticate the user. The result ...

Update the second dropdown automatically based on the selection in the first dropdown menu

I need assistance with creating two dropdown menus that are linked, so when an option is selected in the first menu, it automatically changes the options available in the second menu. Both menus should be visible at all times. I have set up a fiddle to pr ...

Ways to develop tests for functions specific to my scenario

Currently, I am attempting to implement a timeout function test within my application. Within the controller: $scope.$watch('toy',function(toyVar){ if(toyVar == 1) { //perform actions } else { $timeout(f ...

Key Enhancements for Functional Stateless Components

How can I accurately assign a key in a functional component, specifically using the 'key' keyword instead of just a general index? I am attempting to use Map in a functional component to generate a list of another element. However, when I try to ...

Optimizing the management of optional post fields in an Express.js application

When creating an endpoint with Express that includes both mandatory and non-mandatory fields in the post request, what is the optimal strategy for handling this? Would it be best to use something like if (field exists in req.body) { set variable } else { ...

the intricacies of resizing a dijit dialog

My dialog is defined as shown below: <div data-dojo-type="dijit/Dialog" id="DetailDialog" class="dijitDialog" ... I have loaded a grid inside the dialog with 10 columns. var dialog = dijit.byId("DetailDialog"); dialog.set("content", this.Details); d ...

Launching a segment from a different page within a foundation reveal modal

With the goal of displaying a modal that contains content from a section on another page when a link is clicked, I encountered a specific issue. For instance: <a href="/otherpage" data-reveal-id="myModal" data-reveal-ajax="true"> Click Me For A Mod ...

Exploring the Evolution of jsAjaxForm from jQuery Version 2.1.3 to Version 3.2.1

I'm in the process of upgrading to a higher version of jQuery (3.2.1) and encountering difficulties with updating the ajax file upload functionality using jsAjaxForm from jQuery v2.1.3. Is there a similar function that performs the same role as jaAjax ...

Is there a way to have my MUI Typography component display a unique image cursor when hovered over?

After some testing, I found that setting the cursor to cursor: pointer works perfectly fine. However, my goal is to use a custom image as a cursor. The image is saved in both my src and public folders, but I seem to be struggling with the syntax when using ...

Angular Tip: Display data in a dropdown using a select element

When I have two select elements and want to display values if they exist: page.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app ...

Express & React: Be cautious of client checksum and style while server-side rendering

Recently delving into the world of React server side rendering, I'm currently working on a small demo utilizing technologies such as React, Redux, React Router, and Material UI. The main issue I'm encountering is the following warning. I am uncer ...

Retrieve particular attributes from an array of objects

I have an array of JavaScript objects structured as follows: let users = [{ "id": 9, "name": "Sulaymon", "family": "Yahyaei", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="deadabb2bfa7b3b1b0b6b99eb ...

Transform JSON into an Array and generate a new Array from a collection of Arrays

I'm struggling with generating a table in Angular2 from JSON data because I need to pivot the information, but my usual method doesn't seem to work for this scenario. Below is an excerpt of the JSON data I am working with: [ { "ValueDate" ...

Top method for combining several external JavaScript libraries into a single one using webpack

Recently, I was diving into the world of webpack tutorial and it struck me that in order to combine everything into one module, scripts need to use require('./xyz'). Until now, I've always written individual scripts and loaded them in HTML u ...

Tips for creating an endless scrolling/loader feature in Nuxt?

Hey there! I am looking to display data after implementing infinite loading. The data is sent asynchronously using asyncData to the page with an ID. Page <script> export default { async asyncData({ $axios, store }) { const customerId = store.g ...

Looking for advice on using the ternary operator in your code? Let us

In my JS file, the code $scope.button = id ? "Edit" : "Add"; is functioning correctly. I am trying to implement it in the View like this: <button name="saveBtn" class="btn btn-primary" tabindex="10">{{person.id ? 'Edit' : 'Add&ap ...

What is the process for creating a progress bar in PixiJS?

Can someone guide me on creating a progress bar similar to the one in PixiJS? Screenshot ...