Creating a Mongoose schema with a predefined key variable

I am currently utilizing expressjs, mongodb, and mongoose. My goal is to update the counts object within the given schema:

var UsersSchema = new Schema({
  username: { type: String, required: true },
  counts: {
    followers: { type: Number, default: 0 },
    trips: { type: Number, default: 0 },
    videos: { type: Number, default: 0 }
  }
})

The issue lies in the update part of the code (not functioning as expected):

var key = 'trips' // set dynamically, could be 'videos' or 'followers'
Users.update({'username': username}, {$set: {'counts.key': 12}}, callback)

A working example that is not dynamic:

Users.update({'username': username}, {$set: {'counts.trips': 12}}, callback)

Any suggestions on how to solve this?

Answer №1

If you want to set dynamic variables in a query, you can do so by creating a variable for $set and using it accordingly.

let key = 'sales';
let dynamicSet = {$set: {}};
dynamicSet.$set["data." + key] = 25;
Customers.update({'name': customerName}, dynamicSet, callback)

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

Using the Javascript $.each method to iterate over elements

this.CurrentComponent.ExtendedProperties is a Dictionary<string, string> obtained from the .Net platform. However, when trying to access the values within this Dictionary on the client side using JavaScript, all objects associated with the property a ...

Choose specific dates from the data pickers based on the membership tiers and level of importance

I am seeking assistance in implementing a date selection functionality with different priority levels assigned to customers. Below is an explanation of the criteria: Customers with level 1 can choose dates from today up to 5 days in the future Cust ...

Display a notification to the user prior to reloading the page

I have created a code for logging attendance at work using a barcode reader. The user simply needs to scan their card with a barcode to register their attendance. let $scannerInput = $(".scanner-input"); $(document).ready(function(){ $scannerInput.focu ...

The React Component in Next.js does not come equipped with CSS Module functionality

I have been attempting to incorporate and apply CSS styles from a module to a React component, but the styles are not being applied, and the CSS is not being included at all. Here is the current code snippet: ./components/Toolbar.tsx import styles from & ...

Identify the ANGLE using JavaScript

I'm experiencing an issue with my WebGL / Three.js game where there is an unhelpful shader program linking error when ANGLE is used for providing WebGL. To address this, I am looking to implement a prominent warning specifically for ANGLE users on the ...

Add an image using ajax in a Django web application

Having encountered an issue within my Django application, I find myself stuck. Despite implementing an Ajax function for uploading a single image to a model, I have yet to achieve success in this endeavor. The problem lies in the fact that although I am ab ...

I encountered a TypeScript error while utilizing the useContext hook in a React application

Initially, I set the value of createContext to an empty object {}. Afterwards, I provided a context with a new value of {username: 'sasuke1'}. However, when I attempt to access the property Context.username, TypeScript raises the following error: ...

Guide: Enhancing Query Context within jQuery Instances Spanning Across Iframes

In my current project, I am facing a challenge with using a jQuery instance across iframes. It's been causing me quite a bit of frustration. Here's the situation: I have an existing web application that loads jQuery (which is aliased as $jq) in ...

Passing variables in Redirect() without exposing them in the URL; a methodical approach

After scouring the depths of the internet, I have been on a quest to figure out how to seamlessly redirect to a new page on my site while discreetly passing a variable without exposing it in the URL like so: www.test.com/?variable=dont.want.this.here I a ...

Launching an image link within the same location on the subsequent page to which it is directed

I'm completely new to creating websites so I may not be using the correct terminology. I've searched with various terms and ideas but haven't found any solutions to help me ask my question effectively or find examples of what I'm lookin ...

Adding numerous items to a blank array in React following receiving a response from an API in React

When I upload 4 images, I receive 4 different URLs one by one. I need to save each URL in a separate object. const [imageURLs, setImageURLs] = useState([]) const handleImageUpload = async(e) => { const files = e.target.files for (let i = 0; i &l ...

Ways to conceal an item by considering the size of a different element

I have a question about displaying content within a div element. I want to show a "show more" button only if the content inside the div exceeds a max height of 530px. Otherwise, the button should remain hidden. Here is the code snippet I'm using: Ja ...

Angular update row and save data to an array

When comparing the data of an edited row with the row just below it, I encounter a specific scenario. In a table containing 5 rows, as I edit records from top to bottom using the provided code snippet, I am able to store the values in an array. The most re ...

The API has been triggered twice

I am currently working on a React component where I have implemented an API call using the useEffect hook with an empty dependency array. However, I noticed that the API is being called twice and I can't seem to find the reason behind it. import { use ...

Server emitting an array with no elements to the client using the Socket.io protocol

In my app's input box, when I type a message I expect it to be sent to the server and then back to the client to update my UI. Sending messages to the server works fine, but receiving information from the socket.io server seems to be problematic as i ...

What is the best way to show an alert() when a user clicks on a marker in Google Maps?

My current setup:view image description ... google.maps.event.addListener(marker,'click',function() { this.map.setZoom(15); this.map.setCenter(marker.getPosition()); console.log('hello world'); this.presentAlert(); // ERROR co ...

Pattern for validating mobile numbers with extensions using regular expressions

I am struggling to combine multiple separate regex validations into one for my mobile number validation requirements. The criteria include validating mobile numbers with a country code or starting with 00, as well as checking if they contain an extension n ...

An issue has arisen with NextJS Link where it is failing to populate an anchor tag

In my React + NextJS project, I am struggling to display a list of products similar to what you would find on an ecommerce category page. Each product is wrapped in a p tag and should link to its corresponding detail page using an anchor a tag. Although t ...

How can I locally store 3D models and textures using three.js?

Currently working on a game using three.js, where each game level is on a different page. However, when transitioning from one level to another, the browser reloads the page which can be quite slow. Is there a way to store 3D models locally so they don&apo ...

What is the reason behind the failure of next/script with Google reCAPTCHA?

Currently, I am in the process of upgrading from next js version 8 to version 11. I wanted to take advantage of the amazing next js feature for "next/script". However, when I tried to implement it for Google reCAPTCHA using "react-recaptcha": "^2.3.10", th ...