Unique identifier naming in MongoDB Realm for dynamic keys

I'm developing a personalized digital Advent Calendar for a close friend. Each day, he gets to unlock and claim a new Steam game.

Within the user account that I created for him in mongodb, there exists a key named "codes" (object) structured as shown below:

_id: blbalbalba
codes: {
   1 : {
      title: GTA V,
      code: AISHD-SDAH-HAUd, 
      claimed_at: ,
   },
   2 : {
      title: Fortnite,
      code: HHF7-d88a-88fa,
      claimed_at: ,
   }
}

The above is just sample data. When door number 7 is opened by the user in the client application, I aim to update the "claimed_at" key with the current date in the object corresponding to key name "7".

I experimented with various approaches like:

const result = await PrivateUserData.updateOne(
  { id: myID },
  { $set: {  "codes.`${door_number}`.date_claimed" : date,   
  } 
  }
);

However, none of these attempts were successful. What did work was using a static path like "codes.5.date_claimed". This way, the object with name 5 successfully had its date_claimed key updated. Now, my question is, how do I implement a dynamic path utilizing a variable instead of a fixed number?

Thank you for your help!

Answer №1

When you have the variable value known before making the query, either of the following options should work.

var door_number=5;
var date= new Date("...");

const result = await PrivateUserData.updateOne(
  { id: myID },
  { $set : { ["codes."+door_number+".date_claimed"] : date}}
);
var door_number=5;
var date= new Date("...");

const result = await PrivateUserData.updateOne(
  { id: myID },
  { $set : { [`codes.${door_number}.date_claimed`] : date}}
);

If the dynamic behavior is dependent on data from the database, please provide a sample data and expected output for better understanding of your requirements.

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

Can you reference document.styleSheets[].cssRules[] by specifying a rule name?

I am trying to modify a specific class property value in JavaScript without using an integer as a pointer or looping through all classes to find a matching selectorText value. This is specifically for changing the language displayed on the webpage. <s ...

Access your Angular 5 application as a static webpage directly in your browser, no server required!

I need to run an Angular 5 application in a browser by manually opening the index.html file without the use of a server. My client does not have access to any servers and simply wants me to provide a package (dist folder) for them to double-click on the in ...

Using jQuery to iterate through an array and reverse its order

Is there a way to loop through an array and change the CSS background color chronologically rather than randomly? Additionally, is it possible to reverse through the same array when the back button is clicked? http://jsfiddle.net/qK2Dk/ $('#right&a ...

Validating embedded documents using native features of Mongodb

I'm grappling with creating a validation rule for Mongodb that will ensure a document, which includes an embedded document, either doesn't have the embedded document at all or, if present, contains mandatory fields. For example, consider a JSON ...

Query regarding JSON format

If I have a database table named User with fields for name, Id, and age, how can I retrieve this data as JSON and send it to a JavaScript page? I want to customize the way the data is displayed on the frontend. Specifically, I need help understanding how ...

Iterating through the startPrivateConversation method in Botkit for a multitude of users

In order to send an update to all my users, I created a new bot controller in a separate js file. To achieve this successfully, I needed to implement a notification function inside the controller's rtm_open function. The goal was to iterate through th ...

NodeJS cronjob failing to trigger Mongoose query callback

I am currently constructing a REST API backend using NodeJS and testing it locally. As part of this process, I am setting up a cron job to clear expired 'login token reset codes' from the database. These codes are created temporarily for password ...

Concerns regarding rendering HTML and drawing in Node.js

Having an issue where node.js is serving an html file with an SVG drawing. The index.html features a chart similar to the line chart found at http://bl.ocks.org/mbostock/3883245 Whenever I try to serve the index.html through the express server, I end up ...

Efficiently Organizing Data Using Coldfusion Loops in Columns and Rows

My issue lies in pulling data from a database to display on my website. I have three keys/attributes (columns) - PostedDate, DataImage, and Source that need to be shown together in one div with the posted date at the top, image in the middle, and source at ...

Establish the editor's starting state

Currently, I am utilizing lexical and aiming to establish initial text for the editor. At the moment, my approach involves hardcoding the initial text, but it seems I cannot simply pass a String as anticipated. Instead, the format required is JSON. Hence ...

Stack the labels of separate datasets on top of each bar in a bar chart using Chartjs: How can this be achieved?

chart.js 4.4.2 chartjs-plugin-datalabels I am aiming to achieve this effect const chartCtr = document.querySelector('#temp-chart1') as HTMLCanvasElement; new Chart(chartCtr, { type: 'line', plugins: [ChartDataLabels], opt ...

AngularJS ng-switch-trigger enclosed within its own ng-switch-wrapper

In my current project, I am working on switching between two buttons that act as their own triggers for the switch. To illustrate further: <span ng-switch on="patientSwitch"> <span ng-switch-when="edit"> <button ng-click="patien ...

Utilizing React for Redirecting to an External Site

I came across a solution for redirecting to an external link, which worked for one of my pages. However, the same solution does not seem to be working for a different page, and I'm unsure of the reason why. redirect.jsx: import React from "react"; ...

What is the process for transforming a key-value object from JavaScript to TypeScript?

I am currently facing a challenge in converting a JavaScript object into a TypeScript version as part of our code refactoring process :( I am struggling to figure out how to properly migrate a JS JSON object into a correct TS format. For instance, consider ...

Attempting to dynamically change the text of a button in JavaScript without any user interaction

I have created a button function that displays a word's definition when clicked. However, I am now attempting to modify it so that the definitions are shown automatically every few seconds using "SetInterval" without requiring a click. I am unsure of ...

What is the best way to stop a jQuery function from applying titles extracted from the first row th's in thead's to multiple tables in a document?

My circumstances: I am new to jQuery and Stack Overflow, seeking assistance for my website project. The challenge: Building a website using Bootstrap 3.3.6 with intricate data tables that need to be stacked dynamically on mobile devices using CSS. It is c ...

What is the best way to direct an Angular2 application when the user manually alters the navigation

I'm currently using the Angular2 sample tutorial app and encountering an issue. When I click on links that navigate to different sections of the application, such as clicking "dashboard" taking me to localhost:3000/dashboard, and "heroes" taking me to ...

Bring in a pair of JSON files and input them into separate columns within the identical collection

In my current project, I decided to use Python with MongoDB. Instead of utilizing PyMongo for importing JSON files, I have chosen to use sub-process as it is recommended for handling larger files. I am facing a scenario where I have two sizable JSON files ...

Tips for modifying an axios instance during response interception

Is there a way to automatically update an axios instance with the latest token received in a response, without making a second request? The new token can be included in any response after any request, and I want to make sure that the last received token ...

What is the proper way to utilize the uppercase method while ensuring that Turkish characters are not permitted?

Here is the code snippet I am working with: <input type="text" style="text-transform: uppercase" /> When using this code, characters like ü are transformed to Ü. However, I want ü to be transformed to U, so for example, Gülay should become GULA ...