In JavaScript, if you check for the existence of a key in an object, it

Recently, I ran into an issue with an undefined error when trying to access a value in a JavaScript object key. I retrieved arrays of objects using the mongoose.find().exec() callback and then checked each object for a specific key.

Here is an example object:

{"promo_id":"5af1c07d5542fc9307847a6a",
  "__v":0,
   "description":"Hello", 
 "available_count":0}
  • When I tested
    obj.hasOwnProperty('available_count')
    , it unexpectedly returned false.
  • Using lodash's _.isObject() method on the object returned true.
  • Ultimately, I had to resort to JSON.parse(JSON.stringify(obj)) to resolve the issue.

I am perplexed by this strange behavior and would appreciate any insights on why this is happening.

let o = {"promo_id":"5af1c07d5542fc9307847a6a",
  "__v":0,
   "description":"Hello", 
 "available_count":0}
 
 let result = o.hasOwnProperty('available_count');
 
 console.log(result)

Answer №1

According to the documentation provided by Mongoose, when you use query.find(), it returns an array of documents. These Mongoose documents are unique in that they do not directly correspond to JavaScript literal objects:

Mongoose documents maintain a one-to-one mapping with the documents stored in MongoDB, with each document representing an instance of its Model.

http://mongoosejs.com/docs/documents.html

If you refer to the Document API, you will find a toObject() method. It is recommended to try using this method on the first item in the returned array.

You may be wondering why JSON.parse(JSON.stringify(obj)) works for you. This behavior can be attributed to the fact that the MDN documentation on JSON.stringify mentions the use of a toJSON method during stringification. If the object being stringified has implemented this method, it customizes the stringification process. In the case of Mongoose documents, as indicated here, they indeed implement this method, leading to correct stringification into a JavaScript Object Literal which can then be parsed by JSON.parse.

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 implementing div wrapping in HTML

I'm in the process of using flexbox on my website. I have 10 div elements that I want to wrap around each other closely without any gaps between them. My goal is to have "4" positioned to the right of "1", instead of creating a new row and moving dow ...

Discover the simple steps to include row numbers or serial numbers in an angular2 datagrid

Currently, I am utilizing angular2 -datatable. Unfortunately, I am facing an issue where the correct row numbers are not being displayed in their corresponding rows. Whenever a user moves to the next page using the paginator, the datatable starts countin ...

I'm having an issue where whenever I click on a different page, I keep getting redirected back to the first page

Upon conducting research, I discovered that by implementing the refined code below, I was able to resolve my issue (my other html was also corrected using this solution) setTimeout(function() { datatable_FTP.ajax.reload(null, false); }, 30000); Although I ...

Uncovering unseen glitches while coding in Vue.js

After changing the page, I noticed that the errors from the form are still visible. Is there a way to make them disappear when navigating away and only show up if I return to the page? Here are the errors I am encountering: <template> <b-form @ ...

Exploring the retrieval of stored information from $localStorage within an AngularJS framework

I have been working on a MEAN app, and after a user successfully logs in, I want to save the returned user data in the localStorage of the browser for future use. I am using the ngStorage module for this purpose. Below is the code snippet from my LoginCont ...

While attempting to utilize inner class functions in Node JS, an error is being encountered

I've been delving into Node JS and exploring how to implement an OOP structure within node. I've created a simple class where I'm using functions to verify and create users in a database. However, I'm encountering a TypeError when attem ...

Instructions for modifying the color of the close button in the angularjs ui-select module

I am currently using ui-select for multiple selection in a dropdown. When an item is selected, it displays a cross button on the upper right corner of the selected item. Is there a way to change the color of the cross button to red? <ui-select multip ...

Is it possible to improve the cleanliness of a dynamic button in Jquery?

I've just finished creating a dynamic button on the screen as per my boss's request. When this button is clicked, it triggers an email window for feedback submission. My aim is to streamline this script so that I can avoid digging into ASP marku ...

Is it necessary to have NodeJs in order to host a React app on a server?

I've been working on a .NET Core 2.2 project with React integration, As I'm nearing completion of the project, I have a query that has been on my mind. Do I need Node.js installed on the server for React to function properly? Thank you. ...

Angular2 and ES6 Promise in JavaScript - tackling the issue of undefined variables

I am working with an array of objects like the one shown below: let PAGES = [ new BasePage( 'home', 'test') ]; let pagesPromise = Promise.resolve(PAGES); My goal is to retrieve a BasePage object by calling the following met ...

HTML5 Slideshow with Smooth Image Transitions

So, I have created an HTML5 image slideshow and it's working perfectly on my localhost. However, I am puzzled as to why there is no transition effect within the slideshow. I was expecting something like fading out the first picture and then having the ...

What is the best way to create a custom hook that updates in response to changes in state?

My situation involves a custom hook that handles a specific state variable. After making changes to the state, it doesn't update right away. To solve this issue, I need to subscribe to it using useEffect. The challenge is that I can't directly ...

What's the reason for text-alignment not functioning properly?

After some testing, I have come up with the following code: .Greetings { width:100%; display:block; text-align:center; font-family: "Times New Roman", Times, serif; font-size:75px; color:#208CB7; } The objective was to center the text on the ...

The Date.UTC function is not providing the correct output

While attempting to change Unix timestamps into a more understandable format, I used Date.UTC(2017,09,23);. When running this code, it returned 1508716800000. However, upon verifying on the website , the displayed result showed October 23, 2017 instead o ...

Leverage multiple services within a single AngularJS controller

Is it possible to use multiple services in the same controller? Currently, I am able to achieve this with different services, but it seems to only perform one service. <!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs ...

Adjusting element position while scrolling

Objective The goal is to have the page navigation display lower on the page by default. This will provide a cleaner layout as shown in the image below. Context An interactive element for navigation was implemented utilizing Headroom.js. This library d ...

Discovering package utilities with npm commands

When integrating a package into my code, such as: import { Text, View, StyleSheet } from "react-native"; How can I discover the full range of utility functions like Text, View, etc. that are available in the react-native package? Is there an n ...

In AngularJs, use ng repeat and ng switch to dynamically generate and display tables

I need help rendering a table with two columns using angularjs directives. <table> <tr ng-repeat="message in messages" > <td ng-switch-on="message.network" ng-switch when="twitter" ng-controller="TweetController"> <span> ...

Utilizing Images with 'General Drawing' in Highcharts

I'm currently attempting to create a task diagram using Highcharts. I had the idea of incorporating images using the <img> tag ren.label('<img src="/images/test.jepg', 10, 82) .attr({ ...

The keys within a TypeScript partial object are defined with strict typing

Currently, I am utilizing Mui components along with TypeScript for creating a helper function that can generate extended variants. import { ButtonProps, ButtonPropsSizeOverrides } from "@mui/material"; declare module "@mui/material/Button&q ...