What is the best way to transfer data from MongoDB to Jade?

Whenever I try to access an object fetched from MongoDB using my client-side JS, I encounter a challenge. Specifically, my goal is to iterate through and utilize the arrays stored within the object. Below is the server-side JS code which effectively retrieves the results and outputs them in the terminal.

app.get("/post/:id", function (req, res, next) {
  var id = req.param('id');
  var query = BlogPost.findById(id).populate('author');

  BlogPost.find(query, {"answers":"true", "blanks":"true", "_id":0}, function(err, results){

  console.log('Results '+results);//This prints an object like:// { answers: [ 'more', 'One', 'more' ], blanks: ['try']}

  query.exec(function (err, post) {
    if (err) return next(err);
    if (!post) return next(); // 404

    res.render('post/view.jade', { post: post, results: results });
  })
})
})

Additionally, here is the jade code snippet:

  #luck
   #{results}

Next, let's take a look at my client-side JS code:

var results = $('#luck').html();
console.log(results.answers[2]);

While the results are correctly displayed on the page, I am unfortunately receiving undefined when I try to log the third answer array element.

Answer №1

If you can see the results displayed on the screen but are unable to navigate through the object, it could indicate a few possibilities:

1) The object might actually be an array, requiring syntax like results[0].whatever instead of results.whatever

2) The object is likely in string format and necessitates calling JSON.parse(results) first before being able to navigate through it

var results = JSON.parse($('#luck').html());
console.log(results.answers[2]);

Answer №2

Appreciate the response @Xinzz, however this jade code snippet:

for outcome in outcomes
     p #{outcome.results}

was the solution that worked for me. I found it here: Utilizing Jade to cycle through JSON

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

Ways to edit specific sub-document fields within an array?

I am facing an issue with updating specific sub-documents within an array of documents in my collection. Despite multiple attempts, every change I make affects all the sub-documents in the array rather than just the ones I target based on their fields. He ...

Optimal approach for implementing AJAX long polling when a Timestamp is unavailable

I implemented AJAX on my page to toggle the display of a message set by an admin in the backend. Here's the JavaScript code snippet I used: $(document).ready(function() { getmessage(); }); function getData() { $.ajax({ ...

Guide to correcting the file path of an external css within the public directory on Express framework

I am facing an issue with loading external CSS files and need some help to fix the path. Despite multiple attempts, I have been unsuccessful so far. Below is my category structure: https://i.stack.imgur.com/sLTcN.png Within the header.ejs file, this is h ...

Removing an item from an ng-repeat loop while also dealing with a FormController within

I am encountering a significant issue with form inputs nested within the ng-repeat directive. I require an input that is an array and can vary in size; allowing users to add or remove parts of the form. Within the ng-repeat directive, there is an ng-form ...

Firestore query is not displaying the expected data, resulting in an empty array being returned

I've encountered an issue where my query is returning an empty array. Despite double-checking for errors and typos in the query, no error messages are popping up. This problem arose while working on a learning project inspired by Firehip's NextJS ...

JavaScript Function to Retrieve URL Parameter in PHPIn this tutorial

I'm currently working on an HTML5 game where each level has its own dedicated HTML page. The results of each level are saved in a JavaScript variable. My question is, how can I pass this information to the next page using the URL? I was considering ...

Mongo Filter based on conditions

I am exploring the possibility of implementing a filter only if the user decides to filter based on certain criteria. Currently, I can successfully filter using $in, but when the criteria specified in the $in filter is not provided, an error occurs reques ...

Attempt to periodically load remote JSON data (error: Origin is not permitted by Access-Control-Allow-Origin)

My goal is to regularly load a .json file containing some information, and here is the code I have come up with: var updateIBEX35 = function () { var ibexText = document.getElementById("IBEX"); let url = 'https://www2.ecobolsa.com/js/data/i3 ...

Vue method not being triggered despite emit in inline template

Trying to figure out what I'm missing here, it seems like this should be the solution: Vue: method is not a function within inline-template component tag Yet, the method still isn't working as expected. <b-table :items="filtered" ...

Fancybox may be difficult to spot when using Safari

Currently, I am utilizing fancybox with the latest versions of jquery.min.js (3.3.1), jquery.fancybox.css (3.5.7), and jquery.fancybox.pack.js (3.5.7). Everything is functioning as expected on all browsers except for Safari. On Safari, the content within ...

Having trouble accessing a folder path from a text file in Photoshop using JavaScript (JSX)

main(); function main(){ var listFile = File("~/Desktop/Testpath.txt"); if(listFile == null) return; listFile.open('r') ; var listString = listFile.read(); listFile.close(); fileList = listString; // &quo ...

Ways to change values in a list of objects within MongoDB

Is there a way to eliminate the "(LIVE)" suffix from each value in the numbers array? { "_id": { "$oid": "601bc57b1ab1854675870d24" }, "name": "Some name", "numbers": [ "APH ...

Ways to synchronize countdown timer on different tabs using the same link

Is there a method available to synchronize a React countdown timer across two separate tabs, for example: 1:46          ||   1:52 first tab     ||   second tab Appreciate any help! ...

Ways to retrieve the text of the <Label> element without relying on the "id" attribute

I have a challenge in extracting text enclosed within the `Label` tag. My knowledge of Javascript and JQuery is limited, so I require guidance on accomplishing this task. Currently, I am attempting to use code that I found on a stackoverflow post titled ge ...

Submit a POST request to my MongoDB database

Greetings everyone, I am a beginner in the world of coding and currently tackling a project where I need help. The project involves creating a website where the client or customer can make a deposit. When they click submit, the form should send a post requ ...

Unable to process login information with form method post on basic login page

Hi, I've been struggling with a simple login page issue. It works fine with Bootstrap, but I want to switch to Angular Material Design. I've been searching for the problem for about 3-4 hours and can't find anything. I suspect that the form ...

What are the alternative methods to execute a React.js application without using react-scripts?

After creating my React.js app using the command below: npx create-react-app my-app I'm now looking to modify the package.json script section to run the app without react-scripts. How can I achieve this? "scripts": { "start&quo ...

JavaScript does not support the enumeration of programs

I'm currently working on a program that takes user input (library, authorName) and displays the titles of books written by the author. Here is an example library structure: let library = [ { author: 'Bill Gates', title: 'The Road Ah ...

What is the process of uploading a file from a Vue.js app to the local public disk in Laravel?

Hello there, I am looking to upload a file from a Vue.js app to the local public directory of Laravel and only store the unique name in MySQL upon form submission. However, I am unsure how to achieve this using JavaScript. // Template Tag <input type= ...

How to ensure a table in MaterialUI always maintains full width without requiring horizontal scrolling in CSS?

After attempting to allocate each widthPercent value on the TableHeader so they sum up to 100%, I am still experiencing the presence of a scroll bar. I have tried setting fixed widths for each column, but this results in excess space on the right side dep ...