Utilizing MongoDB Data in HBS Template Rendering

Attempting to showcase data from my mongodb backend on an hbs template by following this tutorial. No errors are shown in server logs or browser console, but no data is visible on the template. Interestingly, it generates HTML markup. Seeking assistance to identify the issue.

*Note: Using express framework (still learning)

app.js:

app.post("/", function(req, res){
     res.render("default", {title:"posts", entries:myRoute.getBlogEntries()});
});

myRoute.js:

exports.getBlogEntries = function(res) {
mongo.connect("mongodb://localhost:27017/myDB", function(err, db){
       if(err) { return console.dir(err); }

       var collection = db.collection("posts");
       collection.find({},{},function(e,docs){
                   res.render("default", {
                       "entries" : docs
               });
         });
});
};

hbs template:

{{#each entries}}
<form method="POST">
  <div class="well">
    <div class="row">
      <div class="col-md-1">
        <div>
          <button type="submit" value="{{_id}}" class="btn btn-lrg btn-primary" name="voteup" title="Vote post up"><span class="glyphicon glyphicon-thumbs-up"></span></button>
        </div>
        <div style="text-align:center;padding-right:5px;padding-top:7px;padding-bottom:7px;"><span class="badge">{{voteCount}}</span></div>
        <div>
          <button type="submit" value="{{_id}}" class="btn btn-lrg btn-danger" name="votedown" title="Vote post down"><span class="glyphicon glyphicon-thumbs-down"></span></button>
        </div>
      </div>
      <div class="col-md-10">
          <h4>{{title}}</h4>
          <label style="font-weight:normal;font-style:italic">Posted: {{published}}</label>
          <div>
            {{body}}
          </div>
      </div>
    </div>
  </div>
</form>
{{/each}}

Looking forward to your help!

Answer №1

It appears that you are utilizing the mongodb driver, however, the specific version was not provided.

collection.find actually returns a mongodb cursor, rather than an array of documents. To obtain the documents, you can utilize toArray:

collection.find().toArray(function(e,docs){
   ...
}

I recommend familiarizing yourself with the library's documentation before using it, as relying solely on assumptions to understand an API may lead to unforeseen issues.

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

What could be the reason for the malfunction of the select (mongoose query)?

I'm trying to retrieve a User's highest score post. To accomplish this, I am querying the Post model and looking for posts where their user._id matches the author in the post. Everything is functioning correctly in this regard. However, my goal ...

What is the process by which Reactjs obtains data from firebase function triggers in a specific manner?

I am currently utilizing express to develop my firebase functions, and while I have a good grasp on creating standard callable functions, I am struggling with the implementation of trigger functions for background operations (such as onCreate, onDelete, on ...

Guide to define maximum image size in Joi or Hapi

Currently, I am facing an issue with nodejs+mongodb. When uploading images on the front-end, the system restricts it to a maximum size of 50kb. However, I would like to increase this limit to 5MB so that larger images (around 1MB or 2MB) can also be upload ...

Issue encountered while setting up NODE.JS dependencies

How can I resolve this issue? After running npm install --save, I encountered the following warning: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupp ...

Exploring the world of Express, EJS, and Node.js

What is the method to generate a page containing a button that, when clicked with onclick(), redirects users to another webpage? ...

Reorganizing Arrays in Javascript: A How-To Guide

I have an array in JavaScript called var rows. [ { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81f4f2e4f3b0c1e4f9e0ecf1ede4afe2eeec">[email protected]</a>' }, { email: '<a hre ...

The type parameter is overlooked by body-parser

When handling inbound requests with a Content-Type: application/vnd.surveymonkey.response.v1+json, I encountered some difficulties using the body-parser. According to the documentation, the body-parser's json factory method should only parse json and ...

How to properly align TableHeader and TableBody contents in a Material-UI table

I am experiencing an issue with a file that is supposed to display a table of data pulled from a database. Although the table does appear, all the data seems to be displayed under the ISSUE NUMBER column, instead of being aligned with their respective col ...

Guide to extracting data from a JSON object in node.js

I'm having trouble with the following code. How can I retrieve TripNo from a JSON object? model.Gps.find({EmpName:empName}, function(e,o){ var jsonvar = JSON.stringify(o); console.log(jsonvar.TripNo); }); Here is the schema: var ...

Requests from external sources are being overlooked by Node.js running on a virtual machine

This is my first time working with nodejs and express, so please bear with me if this question seems basic. I recently set up nodejs and express on my Debian virtual machine and created a hello-world application. To run it, I used the command: DEBUG=myap ...

Dependencies in AngularJS factories

I'm currently using AngularJS to extract data from mongodb. I have been attempting to utilize a factory to retrieve this information through the $http method. Despite researching and trying numerous approaches, none seem to work for me. In addition t ...

Reading text file lines in batches using Node.js

I am currently exploring a way to establish a Node.js Stream in order to read a text/CSV file iteratively as a Stream. This method would involve: Reading a batch of lines Pausing the reading process Conducting asynchronous processing: Converting all lines ...

Simple image uploading with Node.js and EasyMDE

I am currently working on implementing the local image upload feature for EasyMDE in my Node.js project. Unfortunately, I haven't come across any functioning examples to guide me through this process. Below is a snippet of my code: const easyMDE = ne ...

How can I prevent writeFileSync from replacing existing data?

When I use this line of code, it deletes all existing data. Is there a method or function that will append the new data on a new line instead? fs.writeFileSync(path.resolve(__dirname, 'quotes.json'), JSON.stringify(quotey)); ...

Having trouble viewing the images that were uploaded with Multer using React, Node.js, Sequelize, and PostgreSQL

Is there a way to enable users to click on the default avatar and upload their own image? Although I can successfully upload files to the database, I'm facing issues in accessing them from the client side. It seems like I might not be storing them cor ...

Exploring the functionality of the 'useBodyParser' option in Nestjs

Issue with 'useBodyParser' in Nestjs Application I am encountering an error when trying to utilize the useBodyParser option on my Nestjs application instance. Error: Property 'useBodyParser' is not found on type 'NestExpressAppl ...

What is the process for obtaining the primary domain from the source with the use of express and node

Currently, I am in the process of developing a web application and I would like to implement a limit based on the request origin domain name. This way, I can verify if the data is being accessed from my domain or by someone else. var app = express(); app ...

Guide on retrieving the innerHTML of all <a> tags within a specific span class

<span class="mgen"> <a rel="tag">Action</a> <a rel="tag">Adventure</a> <a rel="tag">Apocalypse</a> <a rel="tag">Fantasy</a> <a rel="tag" ...

The execution of events.js failed at line 136, causing an unhandled 'error' event to be thrown

Why do I keep getting events.js:136 throw er; Unhandled 'error' event and how can I fix it? I have already tried reinstalling both nodejs and mongodb, but the error persists. package.json { "name": "bookstore", "version": "1.0.0", "description" ...

The event handlers on all elements are not loaded when the HTML page is rendered

Currently in the process of developing a project which involves a web server app built with nodejs + express and some client views that are rendered using ejs. In the main app.js file, the following code is present: const express = require('express& ...