Retrieve particular key from document in MongoDB based on provided value

My Document retrieval process looks like this:

async findOne(id: string) {
    return await this.gameModel.findById(id);
}

async update(id: string, updateGameDto: UpdateGameDto) {
    const game = await this.findOne(id)

    // This code snippet prints all keys as expected
    for( const key in game){
        console.log(key)
    }
    // ...
    const keys = Object.keys(game) // [ '$__', '$isNew', '_doc' ]
    return;

}

Why is Object.keys(game) only returning those 3 keys? This limitation prevents me from accessing specific keys using the method below:

const specificKeyByValue = Object.keys(game).find(key => game[key] === "SomeValue")

I could resort to creating a function that retrieves the key with a for loop like so;

const getKeyByValue = (obj, value) => 
{
    for( const key in obj)
    {
        if(obj[key] === value) return key;
    }
}

However, I would rather avoid creating additional functions if possible. Can anyone explain why this particular version of Object.Keys() is not functioning correctly?

Answer №1

There are some distinct differences in how Object.keys and for-in behave.

for-in loops through all enumerable properties of an object that are keyed by strings (excluding those keyed by Symbols), including inherited enumerable properties.

According to the MDN documentation, this is what for-in does:

The loop will go through all enumerable properties of the object itself as well as those inherited from its prototype chain (properties of closer prototypes take precedence over those of prototypes further away from the object in its prototype chain).

A for...in loop only goes through enumerable, non-symbol properties. Objects created from built-in constructors like Array and Object have inherited non-enumerable properties from Array.prototype and Object.prototype, such as Array's indexOf() method or Object's toString() method, which won't be included in the for...in loop.

And here is the distinction (documentation)

Object.keys() returns an array with string elements representing the enumerable string-keyed property names discovered directly on the object. This mirrors iterating with a for...in loop, except that a for...in loop iterates through properties in the prototype chain too. The order of the array returned by Object.keys() matches that given by a for...in loop.

View some examples here

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

Show a mpld3 graph in an HTML page using the Django framework

Incorporating mpld3 to showcase matplotlib charts within an HTML page through django has been my recent focus. I utilize the mpld3.fig_to_dict method to convert a matplotlib figure into a JSON string and store it in a variable. However, I am encountering ...

Retrieve the value of a CSS class property regardless of whether it is actively being utilized

I am facing a dilemma where I need to determine the value of the 'width' property for a css class named 'foo' (example: ".foo { width:200px}" ). However, there may not be an element with this class in the dom yet. My goal is to retrie ...

Enhance the Header component by incorporating a logout button that seamlessly navigates with the NextJS App

Currently, I am utilizing NextJS 14 with App router alongside Spring Boot on the backend. Within my application, I have both public and private routes set up. For the private routes, users are required to log in through a designated login page. Upon succes ...

Issue with TypeScript type narrowing when working with union types

Why is it that the type narrowing isn't functioning in these code snippets? const data: { num: number } | { str: string } if ("num" in data) { data // { num: number; } | { str: string; } } Even after adding a type discriminant, the issue persists ...

Is it true that loading "undefined" into an array can use up a significant amount of memory?

I've encountered a strange issue where a bug is consuming excessive memory and leading to frequent server crashes. Every 30 seconds, a value is saved to an array: historicalValues.push( valueToSave ) When valueToSave is set to 1, the memory usage r ...

What could be the reason for the malfunctioning of the "subscribe" button?

Whenever the subscribe button is clicked, it should send an email to the "subscriptions" section of the database. Unfortunately, when I click the button, nothing seems to happen. My understanding of this is very limited and I can't seem to troubleshoo ...

Prevent Camera from Rotating Outside of Set Time Frame

In my current VR game project using THREE.js, I am attempting to constrain the camera rotation on the y-axis within specific angles to prevent users from seeing behind them. Instead, they should only be able to look left and right. Although I am uncertain ...

"Encountered an error with resolving the dependency tree during the installation of npm react-facebook-login, known as ERESOLVE

Having trouble installing npm react-facebook-login in my react application due to dependency errors. It's a bit daunting, and I'm hesitant to forcefully install something that could lead to issues down the line. Since I am new to JavaScript, what ...

I am facing issues with testing a service in Angular that utilizes the HttpClient

Currently, I am working on an Angular 5 Project, but it's not a major project. However, I haven't been involved in the Angular2+ environment since early 2.1/2.2. My issue revolves around a Service that makes a call to a public API. Unfortunately ...

Dealing with CORS error when making requests to Firebase Realtime Database API within a Vue project

I am currently working with vue-2 and I need to perform a shallow query on the Firebase real-time database by fetching an API. However, when running on my development server, I encounter a CORS blocked issue. What steps should I take to resolve this? PS: I ...

Associations in Typescript Sequelize

There are two simple models in a 1:N relationship - one student has many tasks. // StudentModel.ts interface StudentI extends Model<InferAttributes<StudentI>, InferCreationAttributes<StudentI>> { id: CreationOptional<number> ...

Is there a way for my component to function seamlessly within another component without the need for redundant code?

Is there a way to avoid repeating code when using my component inside another component? For example, in the file NextPage.js, the <LogoutButton/> component does not perform its function. How can I ensure that the <LogoutButton/> behaves the s ...

What is preventing the click event on this dynamically generated checkbox using jQuery?

Check out the jsFiddle Currently, I am utilizing a jQuery plugin that enables users to draw boxes within a designated area. Using jQuery, I have incorporated a checkbox (alongside a dropdown list) into the box that appears when the user releases the mouse ...

Sending information to components in Angular using Router

Should I pass data through the angular router to a component, or is it better to use a service? Currently, the component is receiving data in the following way: this.account = activatedRoute.snapshot.data.account ...

What is the best way to supply JSON data to the "The Wall" MooTools plugin while feeding?

I came across this amazing plugin called "The Wall" but unfortunately, neither the documentation nor the examples demonstrate how to utilize JSON objects with it. Imagine we have a JSON array like: [ { href : "/my/photo/image1.jpg", title : "Me an ...

Error Message: Execution Not Recognized and Missing Requirement

After going through numerous threads, I couldn't find a solution to my specific issue. It's quite unclear what I've installed or uninstalled, but I'm hoping that this error message and its details might provide some clarity. Even though ...

The font family of Material-ui ToolbarTitle is no longer retained

https://i.sstatic.net/ygdwe.png The tutorial mentioned that the title should be styled with the Roboto font, just like the Options title above. However, despite including the Roboto font via a CDN in my project, the font does not appear as expected in my o ...

Having trouble passing multiple associative array values from JavaScript/AJAX to PHP

We have been encountering an issue when trying to pass multiple associative array values from JavaScript/AJAX to PHP, as the PHP file is receiving an empty object/array. Could someone kindly assist us in retrieving the values of an associative array from ...

Creating unique page styles using global styles in Next.js

I am facing a dilemma in my NextJS app. On the /home page, I need to hide the x and y overflow, while on the /books page, I want the user to be able to scroll freely. The issue is that Next only allows for one global stylesheet and using global CSS selec ...

Avoid triggering jQuery "change" event manually in order to prevent unintentional execution when done programm

In my invoicing system, I have implemented a feature where users can select an item using jquery select 2. Upon selection, the base price and other details are automatically filled in the form. Users also have the option to manually change this price befor ...