If an object is discovered in the array, increase its value; if not, add it to the array

I am facing a challenge with executing an updateOne() query on my database. The objective is to increment a specific value in a document if an object within an array in the document has an _id that matches a certain value. If there are no matches with that _id, I need to push a new object to the array.

Here is the simplified schema:

const userSchema = new Schema({
    _id: String
    counting: [{
        _id: String,
        score: Number
    }]    
})
const UserModel = mongoose.model('User', userSchema)

Below is the attempted query which is not functioning as expected, along with example _id values:

const userId:     '5'
const countingId:  '2'

await UserModel.updateOne(
    { _id: userId},
    { counting: {
        $cond: { 
            if: { $in: [ countingId, '_id' ] },
            then: { $inc: { 'score': 1 } },
            else: { $push: { _id: countingId, score: 1 } }
        }
    } }
)

Assuming the current database contains a document like this:

{
    _id: 5,
    counting: {
        _id: 2,
        score: 50
    }
}

After executing the query, the document ends up like this:

{
    _id: 5,
    counting: {
        score: 0
    }
}

When the query finds a match with the countingId, it mistakenly removes the 'counting._id' field and resets the score to 0. If no matches are found, nothing changes. I seek assistance in understanding why this query fails and how I can rectify it.

Answer №1

Since I was unable to find a way to consolidate it into a single query, I decided to separate it into two queries along with an if statement.

if ( await User.findOne({ _id: userId, 'counting._id': countingId }) ) {
    await User.updateOne(
        { _id: userId, 'counting._id': countingId },
        { $inc: { 'counting.$.score': 1 } }
);} else {
    await User.updateOne(
        { _id: userId },
        { $push: { counting: { _id: countingId, score: 1 } } },
        { upsert: true }
)};

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 to Refresh Javascript Functionality in Rails 5 after an Ajax Update?

After exploring my Javascript issue, I've identified the problem post an AJAX call that refreshes a div's content. The core issue is that the contents within the div become unlinked or uninitialized for the Javascript. My goal is to allow users t ...

MongoDB update operation leading to duplicate entries in nested documents using C#

interface Nameable { string Title { get; set; } } class Mother : Nameable { public string Title { get; set; } public List<Offspring> Children { get; set; } = new List<Offspring>(); } class Offspring { public string Title { g ...

Do you have a Wordpress site featuring basic software applications?

I have a question about creating a Wordpress website that involves implementing algorithms to solve tasks based on user input. I'm wondering if it's possible to achieve this without using PHP, and if so, what options are available for doing so. ...

Does this Loop run synchronously?

Recently, I crafted this Loop to iterate through data retrieved from my CouchDB database. I am curious whether this Loop operates synchronously or if async/await is necessary for proper execution. database.view('test', 'getAllowedTracker&ap ...

Dealing with JavaScript Events

I have developed an amazing plugin called https://github.com/suprMax/Zepto-onPress Everything works perfectly except for one small issue. When I receive a callback function, I need to store it along with my actual event handler so that I can detach it whe ...

Styling Bootstrap radio toggle buttons using CSS

I am currently utilizing Bootstrap version 3.37 and have implemented two toggle buttons for users to select from. My goal is to have the "active" state assigned to the blue button when clicked, displaying a dark color. Conversely, when the green button is ...

AngularJS dropdown menu for input selection binding

Hey there, I need some help with the code below: <input type="text" class="form-controlb" ng-model="item.name" id="name" placeholder="Enter Name" /> Also, I have a dropdown as shown here: <div class="col-sm-12" ng-model="query"& ...

What is the reason behind the occurrence of an error when attempting to iterate through an array of objects within my react.js component?

Here is an example of some code: class Stepper extends Component { state ={ quiz_data: [ patient_data: [ {name: "A", age: "1"}, {name: "B", age: & ...

Struggling to create a regular expression for a particular scenario

I'm dealing with nodes and currently faced with the task of applying a UNIX-like grep command to filter out specific content from an HTTP GET response. Below is the raw text received as the body variable: <?xml version="1.0" encoding="UTF-8" stand ...

Tips for retrieving nested JSON objects

I'm struggling to access the nested JSON object values through iteration. Even after attempting console.log(test[0].Invoice[0].Cost.NO[0]);, I still can't get it to work. var test = [{ "Invoice": { "NO": "869", "$$hashKey": "object: ...

Is there a way to exclude specific elements from the object before returning it, instead of returning the entire object?

When the user object is returned, certain fields like password, confirmationToken, and __v are hidden. Here is an example of the user object before filtering: { "user": { "_id": "566786", "detail": { "lastUpdate": "2015-01- ...

What could be causing my cmd to report an error stating that it is unable to locate the node-modules

https://i.sstatic.net/4ztfB.png Take a look at my command prompt below. Do I need to keep the module folder and the code folder in the same directory? ...

Tips for preventing the repetition of code blocks in node.js

Within my code block, I encountered a situation where the if and else blocks contain almost identical code. The only difference is due to one function call with a callback that requires repeated code in both blocks. While I am aware that creating a funct ...

What is the best method for checking for JavaScript errors when using Selenium WebDriver in conjunction with NodeJS?

When it comes to coding in JavaScript, not Java, my focus is on running a specific website like foo.com. I typically set it up as follows: var webdriver = require("selenium-webdriver"); By = webdriver.By, until = webdriver.until; var chrome = req ...

If there is no input, MongoDB will retrieve all documents

Currently, I am utilizing aggregate and match operations to extract data from the database. The code snippet below offers an abridged version of my approach: Palette.aggregate([ {"$match": { type: paletteType, numberOfColors: {[colorNumb ...

Difficulty with Pomodoro clock's canvas ring function not working as expected

Hey everyone, good evening. I've been struggling with a particular section of code for quite some time now and could really use some help. When you check out the constructor at this.drawArc and then look into the prototype, I've printed a couple ...

A guide to checking an array of objects by their ID and assigning a new property using JavaScript

I am working with two arrays of objects called arr1 and arr2 If the ID in both arr1 and arr2 matches, I want to add the property names from arr1 to arr2 using JavaScript var arr1 = [ {id: 1, name : "Helena"}, {id: 2, name : "John"} ...

Enhance the appearance of 6 image URLs by wrapping them in dynamic divs with the

Can someone assist me in displaying 6 images retrieved from a MySQL database on an MVC Razor view? Images 1 and 6 should be placed in separate divs labeled "item", while images 2, 3, 4, and 5 should be grouped together in a div called "item-small". Below i ...

Is jQuery's $.trim() function reliable or poorly implemented?

$.trim() utilizes a specific RegExp pattern to trim a string: /^(\s|\u00A0)+|(\s|\u00A0)+$/g However, this can lead to some issues, as demonstrated in the following example: var mystr = ' some test -- more text ...

Filtering Results Efficiently Based on Various Criteria in React

To view my project in action, please visit my sandbox here. Due to limitations, I am unable to paste all of the code directly here. The goal of my project is to create a tours filtration system based on multiple criteria. Each tour is represented as an ob ...