Tips for updating a specific object's value within an array of objects in Mongoose and MongoDB

I want to implement an award system and I'm exploring the most efficient approach to achieve this. Each time a specific award is earned, I need to increase its corresponding value by one. Here is what my model structure looks like:

 const CardSchema = new mongoose.Schema({
  awards: {
    "awardOne": 0,
    "awardTwo": 0,
    "awardThree": 0,
    "awardFour": 0
  },
  userId: {
    type: mongoose.Schema.ObjectId,
    ref: 'User',
    required: true
  },
})

What would be the optimal method for incrementing, let's say, awardOne by one?

exports.awardCard = asyncHandler(async (req, res, next) => {
  const id = req.params.id;
  const awardOption = req.body.award; //Name of the award
  const card = Card.findById(id)

   if(!card){
        res.status(200).json({
        success: false,
        message: "Card not found"
   }

  card.update ... //Uncertain about how to handle the update here

  card.save()

  res.status(200).json({
    success: true,
    card
  })
});

Answer №1

function giveAwardToCard(req, res) {
  const id = req.params.id;
  const awardType = req.body.award; //Name of the award
  const cardToUpdate = Card.findOneAndUpdate({"_id": id}, { $inc: { [`awards.${awardType}`]: 1 } }, {new: true});

  if (!cardToUpdate) {
    res.status(200).json({
      success: false,
      message: "No card found"
    });
  }

  res.status(200).json({
    success: true,
    updatedCard: cardToUpdate
  });
}

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

A guide to extracting functions from a `v-for` loop in a table

Beginner here. I am attempting to create a dropdown menu for the div with an id matching my specific name. For instance, let's say my table column names are: A, B, C. I only want to have a dropdown menu for column A. The template of my table looks ...

The error pymongo.errors.CursorNotFound occurs when the cursor with the specified ID is not found on the server

I am attempting to export around 1 million documents from MongoDB to a CSV file using PyMongo. Below is my code snippet: import csv from pymongo import MongoClient from datetime import datetime from bson import json_util from tempfile import NamedTemporar ...

Trouble with Bootstrap 5 Carousel swipe functionality: Issues arise when inner elements with overflow are involved, causing vertical scrolling to interfere with left to right swipes

I've been scouring the internet for answers to my unique issue with a Bootstrap 5 carousel. My setup is fairly basic, but I've removed the buttons and rely solely on swiping to navigate through the carousel items. When I swipe left to right, eve ...

Repeated failures in the CodeIgniter JavaScript function

Currently I am developing a donation store using CodeIgniter. I have been focusing on implementing the cart functionality, and have created a small card to display the store items. The card allows users to add items to their cart using an AJAX request to p ...

Can you explain the contrast between passport-google-oauth and passport-google-token for me?

Currently, I am in the process of validating my node application with Google. As I was following different tutorials, I noticed two modules being referenced. I am curious to know what sets these modules apart. passport-google-token Both modules are des ...

Exploring Meteor's Powerful Image Gallery Feature

Currently working on developing a website using meteor. One important feature of the website will be displaying galleries of images. I'm looking for an efficient way to store information about the images and either the actual images or links to them i ...

"MongoDB Aggregating Data with Nested Lookup and Grouping

I have 3 collections named User, Dispensary, and City. My desired result structure is as follows: { _id: , email: , birthdate: , type: , dispensary: { _id: , schedule: , name: , address: , phone: , u ...

What is the best way to retrieve the browser language using node.js (specifically express.js)?

element, consider the scenario where a user requests a specific page and you are interested in determining the language set in their browser on the server side. This information is crucial as it enables you to customize the template with appropriate messa ...

Verify MongoDB connection with Locomotivejs before executing any tasks

Before making any queries to MongoDB within a LocomotiveJS server, I need to ensure the connection is in a "connected" state and reconnect if not. One approach could be to include this check in the before filters. Is there a way to define a global before ...

having difficulty updating password with mongoose

My website is built using MongoDB, mongoose, ejs and NodeJS. I am encountering an issue with the update password function on my site. After reviewing the code and checking various console logs, it seems that the problem lies within the controller. Here is ...

Why isn't my NPM package functioning properly within the Laravel framework?

I recently developed an npm package for my personal use, but encountered a ReferenceError when attempting to utilize it in a Laravel project. Here's the breakdown of what I did: I followed a tutorial on initializing an npm package, and it functioned p ...

Passing a string to a function in AngularJS through ng-click

How can I pass a string to a function using ng click? Here's an example: HTML <a class="btn"> ng-click="test(STRING_TO_PASS)"</a> Controller $scope.test = function(stringOne, stringTwo){ valueOne = test(STRING_TO_PASS); } Edit - ...

Is it possible to achieve the expected outcome at the end of an arrow function without using the filter method?

Here's the coding section - {data?.results ?.filter(item => { if (searchTerm === '') { return item; } else if ( item.title .toLowerCas ...

Issue with Reddit example in Mozilla Addon SDK documentation on the second page

While developing my own addon, I encountered a problem that also occurred with the Reddit example. To simplify things, I will refer to the Reddit example in this explanation. When using the code provided in the example found here, this is the issue that a ...

Is there a way for me to choose a single file while executing the migrate-mongo up command?

Hey there! I'm looking to execute the command migrate-mongo up in just one specific file. Currently, when I run the command migrate-mongo up, it processes all pending migration files. Is there a way to target only one file for execution? For example: ...

Performing mongodb aggregation operations with Golang

My mongodb collection has the following structure: { source: "...", url: "...", comments: [ ..... ] } To find the top 5 documents based on the number of comments, I used the following query in the command prompt: db.gmsNews.aggr ...

As soon as my fingers grace the keyboard, the website springs to life before my

My Node/Express application is displaying some unexpected behavior that I'm struggling to understand. When I start typing the URL, the webpage instantly loads, all logs are populated, and I see my home screen. Currently working on local instance for b ...

Preserve the hidden div selection stored in an array even after the page is refreshed

I have a created a function that toggles between displaying one or all of the divs, based on user selection. Here is my script: <script type="text/javascript"> function switchdivs(theid){ var thearray= new Array("div1", "div2", "div3"); for(i=0; i&l ...

Using discord.js within an HTML environment can add a whole new level of

I'm in the process of creating a dashboard for discord.js, however, I am facing difficulties using the discord.js library and connecting it to the client. Below is my JavaScript code (The project utilizes node.js with express for sending an HTML file ...

I'm looking to fetch my post request with JavaScript - does anyone know how to

In my current setup, I have two main projects. The first project involves using Node.JS for handling data transfer tasks. jsonobj = JSON.stringify(generateMockData) xhrToSoftware.send(jsonobj); xhrToAPI.open("POST", "http://127.0.0.1:8000/pa ...