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?