Retrieving the value from an Object within a Mongoose query result

My query looks like this

const result = await Form.findOne({ _id: req.params.id });

And here is the output of my query:

{ _id: 5a8ea110d7371b7e5040d5c9,
  _user: 5a5c277f8d82ba3644b971c2,
  formDate: 2018-02-22T10:53:04.579Z,
  formElement: 
   { formName: 'Vanilla Form',
     pixel: '23423325',
     fieldRows: [ [Object], [Object] ] },
  formStyle: 
   { globalColor: [ [Object], [Object], [Object] ],
     elementSizing: 'medium',
     elementStyle: 'radius',
     fontFace: 'Open Sans',
     fontSize: { label: '15', button: '15' } },
  __v: 0,
  status: true }

I am attempting to retrieve the pixel value like this

console.log(result.formElement.pixel)

However, when I try to access the pixel value, it returns undefined.
What could be the issue?

Update
Here is the updated portion of my code:

app.get("/view/:id", async (req, res) => {
    const result = await Form.findOne({ _id: req.params.id });
    console.log(result);
    console.log(result.formDate); //returns 2018-02-22T10:53:04.579Z
    console.log(result.formElement.pixel); //returns undefined
    // res.render("form", {
    //  result
    // });
});

I have tried modifying my code by using Promise instead of async, but I still encounter the same issue of getting an undefined value.

Answer №1

In order to retrieve data, make sure to utilize the exec() function, which will return a promise.

app.get("/view/:id", async (req, res) => {
    let retrievedData = await Form.findOne({ _id: req.params.id }).exec();
    retrievedData = JSON.parse(JSON.stringify(retrievedData));
    console.log(retrievedData);
    console.log(retrievedData.formDate); //outputs 2018-02-22T10:53:04.579Z,
    console.log(retrievedData.formElement.pixel) //outputs 23423325
    // res.render("form", {
    //  retrievedData 
    // });
});

Answer №2

To unravel this, roll up your sleeves and engage in some thorough investigation. Inject additional console.logs to troubleshoot the root cause. I suggest initiating by displaying the result to gain clarity on its nature. It's possible that you're attempting to unveil the result prematurely before the await operation concludes. Without visibility into your code snippet, it's challenging to pinpoint the exact moment when you intend to reveal any output.

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

React component attempts to display content before receiving data from API_FETCH, causing rendering issues

I have encountered an issue while fetching data from a crypto API that provides data for 250 coins. Everything works fine when I retrieve data for only 100 coins. However, when I attempt to load data for all 250 coins, the data gets rendered prematurely an ...

What is the best way to capture source code and store it in a text file?

Can you assist me in extracting the source code of a webpage and saving it into a text file? My goal: Instead of going through the process of right-clicking on the page, selecting view source code, copying, and pasting into a text file... I want to simpl ...

Middleware for handling asynchronous operations in Express applications

We are currently working on a custom analytics backend for our NodeJS Express application. The next step is to decide how to implement the tracking mechanism for browsers with JavaScript disabled, such as feature phones. One potential design approach we a ...

Guide on sending AJAX requests from Javascript/React to Python REST API and receiving data

In my project, I have developed the front end code using React. There is a simple form where users can input their name, title, department, and other basic string fields. Upon hitting submit, JavaScript triggers an AJAX request to my REST API which is impl ...

The onclick event is malfunctioning in Chrome when dealing with data driven by SQL

<select id='city' name='city' > <?php $dbcon = mysql_connect($host, $username, $password); mysql_select_db($db_name,$dbcon) or die( "Unable to select database"); $city_query = "SELECT city,county FROM citycatalog order by city ...

Plugin for Vegas Slideshow - Is there a way to postpone the beginning of the slideshow?

Is there a way to delay the start of a slideshow in JavaScript while keeping the initial background image visible for a set amount of time? I believe I can achieve this by using the setTimeout method, but I'm struggling to implement it correctly. Be ...

JavaScript horizontal slider designed for a seamless user experience

Currently, I am in the process of developing a slideshow that includes thumbnails. While my slideshow is functional, I am facing an issue with limited space to display all thumbnails horizontally. I am considering implementing a horizontal slider for the t ...

Tips for setting up Express to consistently serve Angular while safeguarding API routes

I need to set up my node-express back-end so that it serves Angular files by default, but handles API routes differently. All API routes should be protected, with the exception of /api/signin and /api/changepass. I suspect that the order of my code is cau ...

The reactivity of VUE 3 arrays is not being updated, but individual array elements accessed using array

Currently facing an issue while trying to connect a dynamically updating array of objects to a Konva circle. The circles are appearing as expected, but the problem arises within a for loop where I update player locations based on a "tick". While setting th ...

In Internet Explorer 10, it is not possible to access the document.links using the link's id; it can only be accessed using the

Why does the following code work in FireFox 23.0.1 and Chrome 29, but not in IE 10? <!DOCTYPE html> <html> <head> <title></title> <script type="text/javascript"> function loadFile1(){ a ...

The function is not being called by ngModelController $parsers in Angular version 1.4.7

I'm encountering an issue with ngModel.NgModelController.$parsers. Let me explain with an example: I have created a directive for an input field. Whenever I change the value in this input in the HTML, it should call my specified function. The registe ...

Can the "value" of an HTML form field rendered by Django be altered?

Essentially, I have a form that includes a radio select widget for the field named Queue. The choices available for the Queue are sourced from a model, which is accessed and defined within the views.py file. To display this form on my template, I am using ...

Leveraging ExpressJS and AngularJS for routing, providing seamless navigation experience without the need

I am currently working on setting up routing functionality for my ExpressJS Server. http://localhost:3000/app/sub_one http://localhost:3000/app/sub_two Unfortunately, I have encountered an issue where I cannot get it to work when using a prefix of # betw ...

Modify the css with JQUERY when there are no rows inside the tbody section

Is it possible to change the css using jquery if there are no rows in the table body? I have attempted this but my current approach is not working. I tried adding an alert within the if statement, but the alert did not appear. My goal is to hide the table ...

How can I reduce the burden of dependencies on users with a pre-built NPM package?

I recently took over maintenance of an NPM package. It has a unique setup where the main file is located in the 'dist/' directory and it's built using webpack (via 'npm run build'). While this works for us, installing this package ...

I am interested in creating an input range slider using React and TypeScript

This code was used to create a slider functionality import { mainModule } from 'process'; import React, { useState } from 'react'; import styled from 'styled-components'; const DragScaleBar = () => { const [value, setV ...

Guide for configuring Quirks mode for Documents in asp.net

Currently, I am using Internet Explorer 10 and I am looking to set the Document mode of the browser to normal Quirks instead of IE 5 quirks for my website. I have tried adding <meta http-equiv="X-UA-Compatible" content="IE=10;IE=9;IE=edge"> in my m ...

What could be the reason behind the disappearance of the lines in my table that was created with the help of HTML, CSS, and JavaScript?

When I added the Modal trigger, the table lines changed. I suspect it has to do with the buttons in the table. I'm new to HTML/CSS/JS so this whole experience is quite different for me. Any advice or tips for future projects would be greatly appreciat ...

The focus behavior of React refs varies across different browsers such as Chrome, Firefox, and IE

While working with refs in react, I observed that the .focus() method behaves differently in Chrome and Firefox. https://i.stack.imgur.com/rjSsZ.png In this sandbox https://codesandbox.io/s/a-guide-to-react-refs-2nd-example-vl9sj?file=/src/Ref.js I have ...

Stop the bootstrap accordion from expanding when a button in its header is clicked

Currently, I am facing an issue with two action buttons located in the header of an accordion. Here is the setup: https://i.sstatic.net/HU2Kp.png Whenever I click on one of these buttons, it toggles the accordion's state. I have attempted to use e.p ...