Using Express and Dust.js to render a list of data items in a view

Currently, my homepage displays the 6 oldest Story posts from MongoDB.

Here is the query I use to retrieve data from Mongo:

var query = Story
            .find({maxlines:10})
            .sort({_id:1})
            .limit(6);

After querying the data, I pass it to dust.js using the following code:

app.get('/', function(req, res){
    query.exec(function(err, story) {
        if (err) console.log(err);
        res.render('index', {
        title: 'Test!',
        storytitle1: story[0].title,
        storylines1: story[0].lines,
        storyid1: story[0].sid,
        storyslug1: slugs(story[0].title),   
        storytitle2: story[1].title,
        storylines2: story[1].lines,
        storyid2: story[1].sid,
        storyslug2: slugs(story[1].title), 
        storytitle3: story[2].title,
        storylines3: story[2].lines,
        storyid3: story[2].sid,
        storyslug3: slugs(story[2].title),    
        storytitle4: story[3].title,
        storylines4: story[3].lines,
        storyid4: story[3].sid,   
        storyslug4: slugs(story[3].title), 
        storytitle5: story[4].title,
        storylines5: story[4].lines,
        storyid5: story[4].sid,  
        storyslug5: slugs(story[4].title),  
        storytitle6: story[5].title,
        storylines6: story[5].lines,
        storyid6: story[5].sid,  
        storyslug6: slugs(story[5].title)     
    });
    });
});

In the .dust template, I have the following structure:

<h1 class="title">{storytitle1}</h1>
        {#storylines1}
            <ul>{text}</ul>
        {/storylines1}

<h1 class="title">{storytitle2}</h1>
        {#storylines2}
            <ul>{text}</ul>
        {/storylines2}

While this method works perfectly fine for rendering each post individually, I am exploring better and cleaner ways to achieve this. Specifically, I am looking for a solution that would allow me to implement another page, like '/all/', which can display a larger number of stories without the need to write them all individually in the template.

Answer №1

Give this a shot.

Snippet:

app.get('/', function(req, res){
    query.exec(function(err, story) {
        if (err) console.log(err);
        for (var i = 0; i < story.length; i++) {
            story[i].slug = slugs(story[i].title);
        }
        res.render('index', {
            title: 'Test!',
            stories: story
        });
    });
});

Template Code:

{#stories}
    <h1 class="title">{title}</h1>
        {#lines}
            <ul>{text}</ul>
        {/lines}
{/stories}

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 is the best way to initiate a node.js application automatically on an Amazon Linux AMI instance in AWS?

Could someone provide a simple guide on how to start an application when the instance starts up and is running? If the service was installed using yum, can I use /sbin/chkconfig to add it as a service? But what if I want to run a program that wasn't ...

Generating a unique user ID similar to Zerodha's user ID using Node.js/JavaScript

For a project I'm working on, I need to create random and unique User IDs. I came across Zerodha's user IDs which are easy to remember. In Zerodha user IDs: The first two characters are always letters followed by four numbers. I want to generat ...

The strategy for synchronizing API calls across multiple tabs in a browser

Can an API be called on multiple browser tabs simultaneously? For instance, in Tab A I make a call to the apple API with data A, and in Tab B I also call the same apple API but with data B. This means that the apple API in Tab A should ...

Trouble arises when attempting to remove an object using a combination of Node.JS, Mongoose, MongoDB, and

In my setup, I have two collections: one is called subcategories and the other is called categories. The categories collection includes a field known as subcategories which is an array containing the ids of the subcategories from the subcategories collecti ...

Combining React, Express, and Nodemailer poses challenges in rendering components and sending emails simultaneously

Looking to utilize client-side routing for my React app and also incorporate Nodemailer for sending emails. However, since Nodemailer cannot be used on the client-side, I need to implement it on the Express server. Here is how the server code looks like: ...

What is the best way to send JSON data from NodeJS to Django?

Our app's architecture utilizes a combination of NodeJS and Django. I am looking to send JSON data from NodeJS to Django without waiting for any prior request from Django. Essentially, whenever a function in NodeJS generates JSON data, it should be a ...

Which service is most recommended for hosting a GCP FTP Node application?

Let me give you some background on our current project. We have weather and soil monitoring stations scattered across the country collecting data that is then uploaded to a server via FTP for processing. Although this server is not currently in the GCP, we ...

An issue has arisen in the production environment on AWS EC2 due to a problem with Nodemailer

When using nodemailer with node.js to send emails, I have set up the following configuration: var transporter = nodemailer.createTransport({ service: 'gmail', host: 'smtp.gmail.com', auth: { ...

Issue with ReactJS/Next.js: Unable to use CRA Proxy to route API requests to Express server

Currently, I am in the process of upgrading a vanilla React application to utilize Next.js (version 7.0.0). The original app was developed using Create-React-App and leveraged the built-in proxy feature of CRA's server. During development, my React a ...

terminate the default browser using Node.js

When using nodejs, the open package allows you to open a default browser. However, what is a good way to programmatically close the default browser using nodejs or bash on Ubuntu? var open = require('open'); open('https://www.youtub ...

Unable to utilize Google Storage within a TypeScript environment

I'm encountering an issue while attempting to integrate the Google Storage node.js module into my Firebase Cloud functions using TypeScript. //myfile.ts import { Storage } from '@google-cloud/storage'; const storageInstance = new Storage({ ...

Encountering a Next.js redirect issue with 'The page is not redirecting properly' in _app.js

I'm currently working on the user authentication section of a nextjs app. The majority of it is done, except for the protected routes. I'm trying to manage the authentication aspect in _app.js. Below is the code snippet: import App from 'nex ...

Generate a customized API key using Node.js and save it in Redis

I'm currently working on setting up an API with Node and my goal is to securely store the API key/access token in a Redis database. What is the most effective way to create a one-of-a-kind API key/access token that can be stored as the key in the Red ...

If values are not provided during an update, they will be automatically set as null in the database

I am looking to update certain keys and values in my database. Currently, I have populated fields such as firstname, lastname, and now I wish to add profile pictures, contact numbers, etc. However, when I use the update method, the fields that are already ...

How many installation packages does Appium require?

Currently, I am in the process of installing the most recent version (1.6.3) of appium using npm. There seems to be an overwhelming number of various packages being downloaded by npm during the installation, and I am uncertain if all of these packages are ...

Having an issue with `console.log` not working in the `public/javascript/` directory in Node

I've encountered an issue where console.log isn't working for me when placed within a function in the public/javascripts folder of my node.js project. My current folder structure is as follows: views routes public javascripts > utils.js Wi ...

Sharing tips for sending error objects to a socket.io callback

Utilizing callbacks with socket.io Client side code : socket.emit('someEvent', {data:1}, function(err, result) { console.log(err.message); }); Server side code : socket.on('someEvent', function(data, callback) { callback(ne ...

NPM has surprisingly opted for an outdated Node version

Upon running node -v on my Linux system, the output is as expected with v16.7.0 due to the binaries installed on my PATH. However, when a scripts element in my package.json calls node -v, it inexplicably prints v9.11.2. What could be causing this discrepan ...

Access to Angular CORS request has been blocked

I'm currently working on establishing a connection between my Angular application and a basic REST server using express. The server responds to requests with JSON data exclusively. To enable CORS support, I've integrated the cors module from npm ...

Issue encountered when trying to access the webpage through a puppeteer connection

I am currently experimenting with web scraping using the puppeteer library to extract data from a Chrome page. I have managed to connect to an existing Chrome page in debugging mode by obtaining the ws URL and successfully establishing a connection. Here i ...