Increasing an element in an array of objects using MongoDB and Mongoose

In my possession is a document structured as follows:

{
  "id": "12345",
  "channels": [
    {
      "id": "67890",
      "count": 1
    }
  ]
}

My objective is to increase the count of a specific channel by one. When a user sends a message, I must locate the user, identify the correct channel by its "id" within the "channels" array, and raise the "count" by one.

I experimented with the subsequent query:

UserModel.findOneAndUpdate({id: this.id}, 
  {'channels.id': channel.id}, 
  {$set: {$inc: {'channels.$.count': 1}}}

To my surprise, the execution did not result in an error. However, the count was also left unaffected.

Answer №1

Just a couple of adjustments needed: make sure the query is a singular object and utilize $inc as a standalone operator, eliminating the need for $set:

UserModel.findOneAndUpdate({id: this.id, 'channels.id': channel.id},
    { $inc: {'channels.$.count': 1}})

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

What is the method for retrieving a JSON type object property that is stored inside a data object in a Vue template?

I am facing an issue with retrieving data from a Vue.js app object. data() { return { group1: { id: 'qd4TTgajyDexFAZ5RKFP', owners: { john: {age: 32, gender: 'man'}, mary: {age: 34, gender: 'wom ...

Exploring the possibilities of utilizing package.json exports within a TypeScript project

I have a local Typescript package that I am importing into a project using npm I ./path/to/midule. The JSON structure of the package.json for this package is as follows: { "name": "my_package", "version": "1.0.0&q ...

Changing the website address | Node.js | Express

Is there a way to redirect incoming requests to different endpoints depending on a query parameter in the request? For instance, http://localhost:9000/?category=xyz&param1=...&param2=... The category value can be any of [abc, ijk, pqr, xyz]. Gi ...

Saving real-time information to MongoDB with Node.js

What is the best way to use JSON.stringify and send it to my mongoDB Database? For instance: import express from 'express'; let data_record = JSON.stringify({**any content**}) This snippet of code will automatically fetch data every 60 second ...

An AngularJS project utilizing exclusively EJB

Can an AngularJS application be built directly with EJB without needing to expose them as REST services? Many examples on the internet show that eventually REST services are required to provide data to AngularJS. This means that EJB methods must be expos ...

Animating SVG while scrolling on a one-page website

Is there a way to incorporate SVG animation scrolling in a single page website? I am inspired by websites like and . The first one stands out to me because the animation is controlled by scrollup and scrolldown actions. I haven't written any of my S ...

When attempting to add or store data in MongoDB, it triggers a 500 server error

Greetings, I am currently working on developing a CRUD app using the MEAN stack. The Express application loads successfully and retrieves the "contactlist" collection from the database. However, when attempting to make a POST request to "/api/contacts", an ...

Encountering difficulties in JavaScript while trying to instantiate Vue Router

After following the guide, I reached the point where creating a Vue instance was necessary (which seemed to work). However, it also required providing a Vue Router instance into the Vue constructor, as shown below. const router = new VueRouter({ routes }) ...

The process of initializing the Angular "Hello World" app

Beginning with a simple "hello world" Angular app was going smoothly until I attempted to add the controller. Unfortunately, at that point, the expression stopped working on the page. <!doctype html> <html ng-app='app'> <head> ...

Using Mongoose to Find Subdocument by Property Value

I am currently working on finding a way to retrieve an array of unpaid orders. Each order subdocument contains a property called isPaid that indicates whether the order has been paid or not. My goal is to only display orders that have not yet been paid in ...

Checkbox remains selected even after navigating back

I am currently working on a code that involves using checkboxes. When I click on them, the checkbox value is appended to the URL with a hash. However, when I go back or press the back button, the URL changes but the checkboxes remain checked. Below is the ...

I am encountering an issue where the POST data is not being successfully sent using XMLHttpRequest unless I include

I have a unique website where users can input a cost code, which is then submitted and POSTed to a page called 'process-cost-code.php'. This page performs basic validation checks and saves the information to a database if everything is correct. T ...

Dealing with errors in a MongoDB query using Node.js

Whenever I call collection.find(someBadQuery) in MongoDB, I encounter an error that leads to an unhandled rejection. How can I properly handle this rejection situation? According to the documentation mentioned here, the find() function in the MongoDB NodeJ ...

Guide to setting up a back button to return to the previous page in an iframe application on Facebook

I've developed a Facebook application that is contained within an IFRAME. Upon opening the application, users are presented with the main site, and by clicking on the gallery, they can view a variety of products. The gallery includes subpages that lo ...

Partial functionality achieved by integrating Bootstrap for a modal form in Rails

Having an issue with a form in a partial view on Rails 3.2.3 utilizing the bootstrap 2.0.2 modals #myModal.modal .modal-header .close{"data-dismiss" => "modal"}= link_to "x", root_path %h3 Add Tags .modal-body = form_tag '/tagging& ...

Issue encountered: Next.js has failed to hydrate properly due to a discrepancy between the initial UI and server-rendered content

Uncertain about the cause of this error? The error seems to disappear when I remove the provided code segment. What is triggering this error in the code snippet and how can it be fixed? <div className="relative flex flex-col items-center pt-[85.2 ...

There is a lag in the loading of css stylesheets

We created a single-page company website that utilizes three different stylesheets connected to the index.html. By clicking a button, users can switch between these stylesheets resulting in changes to colors, images, and text colors. However, Issue 1: The ...

Ways to generate arrays in Typescript

My dilemma lies in a generator method I've created that asynchronously adds items to an array, and then yields each item using yield* array at the end of the process. However, TypeScript compiler is throwing me off with an error message (TS2766) that ...

Steps for inserting a JSON Array into a database

I have a dropdown menu that displays different options based on the selection from another dropdown. The data for each dropdown is fetched from the database and I need to insert the selected values into a new table in the database. All the necessary code ...

What methods are available for drawing on an HTML canvas using a mouse?

I am facing two challenges: how can I create rectangles using the mouse on an HTML canvas, and why is my timer not visible? Despite trying various code snippets, nothing seems to be working. Grateful for any help! HTML: <!DOCTYPE html> <html lan ...