0

I'm trying to deconstruct this data so that I can use it within an EJS template:

Promise {
  [
    {
      _id: new ObjectId("62ef1ea68a82d65948539324"),
      title: 'Test Title',
      picture: 'n/a',
      body: 'this is the body of the test post'
    },
    {
      _id: new ObjectId("62ef202670ad070b78e928a3"),
      title: 'Test Title 2',
      picture: 'n/a',
      body: 'this is the body of the second test post'
    }
  ]
}

I'm trying the following:

<%-include("header")-%>
<h1>Posts:</h1>
<% for (var i =1; i < 2;  i++ ) { %>
    <p><%= blogPosts[i] %></p>
    <% } %>
<% console.log(blogPosts); %>
<%-include("footer")-%>

For context, here's the js file that generates the promise:

// const { response } = require('express');
// Connect to database instance.
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/blog', {useNewUrlParser: true});

// Define database schema.
const Schema = mongoose.Schema;
const BlogSchema = new Schema({
    title : String,
    image: String,
    body: String
});

const Model = mongoose.model;
const BlogPost = new Model('posts', BlogSchema);

async function getBlogPosts(){
    /**
     * Connect to the database and pull all of the blog entries.
     */
    try {
        const allPosts = await BlogPost.find({});
        return allPosts;
    } catch(error) {
        console.log("We ran into trouble fetching blog entries.");
    };
};

async function main(){
    /**
     * Main blog program
     * Returns object allBlogPosts for use in the blog template.
     */
    // Load all of the blog posts for future use.
    const allBlogPosts = await getBlogPosts();
    return allBlogPosts;
};

// // Calling the main program as an export to kick things off.
module.exports = main();

This is how we're passing the promise to EJS in the primary js file:

app.get('/blog', function(req,res){
    // import the blog module, which returns a promise object
    // containing all the blog posts retrieved from the db
    const blogPosts = require('./blog');
    // render the blog template with year for the footer and blog posts
    res.render("blog", {currentYear: currentYear, blogPosts: blogPosts});
});

The console.log produces what I expect, and proves that the data is available to the EJS template. When I render the page though, I don't get anything. There is no HTML produced for me to leave here. What's the best way to deconstruct this promise to make it iterable?

  • 1
    if `blogPosts` is indeed a **Promise** then you have to wait for the promise to resolve before you can use the values it resolves to ... also, your "loop" will access exactly ONE element of an array ... the second one (index 1) ONLY - but then, if `blogPosts` is a Promise, then that isn't an Array anyway – Jaromanda X Nov 08 '22 at 02:20
  • the console.log shows what you want, because the value shown is evaluated when you view it, not when you log it – Jaromanda X Nov 08 '22 at 02:23
  • You'll need to wait for the promise *before* passing the value into the ejs template. Please show us that part of your code if you need further help. – Bergi Nov 08 '22 at 02:33
  • Added additional information – Concentravity Nov 08 '22 at 21:14

0 Answers0