JS: Use either $addToSet or $pull based on the current availability of the value

I am looking for a more efficient way to add or remove an ID from an array (target) in an Articles object, based on whether it already exists. Currently, I am using the following approach:

var isExisting = Articles.findOne({ _id }).target.indexOf(mID) > -1

if (isExisting === false) {
  Articles.update(
      { _id },
      { $addToSet: { target: mID } }
    )
} else if (isExisting === true) {
  Articles.update(
    { _id },
    { $pull: { target: mID } }
  )
}

Could there be a more optimal way to achieve this without the need for if/else statements and a minimum of two database operations?

Answer №1

Executing Mongoose operations asynchronously means waiting for the callback to retrieve the document.

// Find the article by its ID
Articles.findById(_id, function (err, article) {
    // Make appropriate changes based on whether mID exists in the article's target
    if (article.target.indexOf(mID) > -1)
        article.target.pull(mID)
    else
        article.target.push(mID)
    // Save the changes
    article.save(function (err) {

    });
})

Although you're using an if/else statement, you're essentially performing two operations.

Answer №2

below is a suggestion to improve the code

const checkExistingRecord = Articles.findOne({ _id: _id, target : mID}) //check if mID exists in array of [mIDs]
const query = { _id : _id };
const updateQuery = checkExistingRecord ? { $pull: { target: mID } } : { $addToSet: { target: mID } };

Articles.update(query, updateQuery);

Do you find this version clearer and more efficient?

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

Experience the frustration when the Ruby on Rails Open Modal Box Link fails to work. Stay tuned for the latest update on the link

My goal is to have a Modal Popup Box open when a specific link is clicked on my page. Here is the code I added to my view file: <%= link_to_remote '+ Add Discount', :url => {:controller => "parent_wise_fee_payments", :action => "ne ...

Exploring the Express problem with AWS SNS web service subscriptions using a Sinatra case study

I'm currently working on developing an auto-subscription API that sends back a token via POST. While I have successfully implemented this in Sinatra (rendering the POSTed JSON from AWS), I'm facing challenges with Express. I believe it's jus ...

Guide on dynamically applying a CSS rule to an HTML element using programming techniques

Currently working with Angular 6 and Typescript, I am facing a unique challenge. My task involves adding a specific CSS rule to the host of a component that I am currently developing. Unfortunately, applying this rule systematically is not an option. Inste ...

Updating language settings on-the-fly in a Vue application does not automatically refresh the translated content displayed on the website

My Vue app is quite large, built with Vuetify, and I recently integrated vue-i18n into it. The json translation files are set up correctly, and the $t() calls work fine in my components and other .js files. However, I'm struggling to change the locale ...

Curious about the method of refining a list based on another list?

As a beginner in coding, I am facing a challenge in my code.org assignment. I need to filter songs by a specific artist from a dataset. Currently, I have code that randomly selects an artist, but I am struggling to filter out songs by that artist from the ...

How can I show the real width of an image on a mobile device?

I have integrated the infinite slide plugin from jQueryscript.net into my website. While it works perfectly on desktop with background images, I am facing an issue on mobile devices where the image width needs to be displayed in full. I attempted to adjust ...

The functionality of the button in my script is limited to a single use

Below is a simple code snippet that I wrote: HTML & CSS: <!DOCTYPE html> <html> <head> <title> JavaScript Console </title> <style> button { text-align:center; ...

finding the index of a particular checkbox in a list

I am working with a list of checkboxes that are dynamically created using JavaScript, each contained within its own separate div element. I need to determine the position number of a specific checkbox within all checkboxes sharing the same class within a p ...

Creating a bot that will only respond once when a user sends multiple photos simultaneously

I'm currently working on a Telegram bot using nodejs. I am utilizing the node-telegram-bot-api library and have implemented the on('photo') method to handle when a user sends a photo to my bot. However, I am facing an issue where if a user ...

When the user clicks, the template data should be displayed on the current page

I need help with rendering data from a template on the same HTML page. I want to hide the data when the back button is clicked and show it when the view button is clicked. Here is my code: <h2>Saved Deals</h2> <p>This includes deals wh ...

Encountering the error "Unable to access the 'pickAlgorithm' property of null" in a ReactJS context

Encountering an issue during npm install process. npm install -g netlify-cli The error message displayed is: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a2a5b0a5a2b5fcb2bdb8b4bfa591e1ffe5ffe6"> ...

The form is not being submitted when I click on the submit button because I have two buttons that trigger AJAX requests

I am facing an issue with a form where there is a submit button inside it, as well as another button within the form that has attributes type=button and onclick=somefunction(). The button with the onclick function works perfectly fine, but the other button ...

Execute a function prior to making a synchronous call

Seeking guidance on a complex issue that I have encountered. In my code, I am dealing with a synchronous AJAX call and need to execute a function before this particular call is made. The function in question is a simple one: $.blockUI(); This function ...

What is the best way to keep a text editable in a razor editor without it vanishing?

I'm on a quest to find the name for a certain functionality that has been eluding me, and it's truly driving me up the wall. Check out the razor code snippet I've been using to exhibit my form inputs: <div class="col-sm"> ...

Storing tweets in a mongodb database using nodejs

I have successfully written a code using nodejs to fetch data from twitter. Now, I am facing difficulty in storing it in mongodb. Can someone please provide me with step-by-step guidance on how to achieve this? I am unable to do it on my own. var app = ...

Which one should I prioritize learning first - AngularJS or Laravel?

As a novice web developer, I am embarking on my first journey into the world of frameworks. After much consideration, I have narrowed it down to two options: AngularJS and Laravel. Can you offer any advice on which one would be best for me to start with? ...

What occurs to the bound event once the DOM element disappears?

What happens if I attach an event handler to a DOM element and then remove the DOM element? Do I need to unbind the event handlers? <div id="el1"> <span id="c">Click Me!</span> </div> <span id="note">Note...</span> ...

"Error encountered in @mui/x-data-grid's ValueGetter function due to undefined parameters being passed

I'm currently using @mui/x-data-grid version 7.3.0 and I've encountered a problem with the valueGetter function in my columns definition. The params object that should be received by the valueGetter function is showing up as undefined. Below is ...

Animation is not applied to Bootstrap Collapse on a row within a table

My Bootstrap 4 table has an issue - when I apply the "collapse" class to a table row, it behaves differently compared to applying it to a div element. Clicking "animate div" smoothly animates the target div, but clicking "animate tr" does not animate the ...

Translate a jQuery ajax request utilizing jQuery().serialize into plain JavaScript

Currently, I've been in the process of converting a jQuery script into vanilla JavaScript to completely eliminate the need for jQuery. The main functionality of the code includes: Upon clicking a button on the front end, an ajax request is sent, upda ...