0

I'm trying to read a JSON file from my database. Here is the rendered page.

    <% newcompose.forEach(function(post){ %>

        <h1><%= post.caption %></h1>
        <p><%= post.text %></p>

    <% }); %>

And this is how i'm passing the value into newcompose.

Post.find({}, function(err, posts){
    if(!err){
        res.render("home", {newcompose: posts});
    }
});

It says newcompose not defined but if I add <% var newcompose; %> to home then it says forEach not defined. also I'm using mongoose.

1
  • have you determined that posts has a value Commented Sep 2, 2020 at 2:44

1 Answer 1

1

I tested your template using the following code:

const ejs = require('ejs');

let template = `
<%newcompose.forEach(function(post){%>
    <h1><%=post.caption%></h1>
    <p><%=post.text%></p>
<%});%>
`;

const renderData = {
    newcompose: [
        {
            caption: "test caption",
            text: "test text",
        }
    ]
};
const output = ejs.render(template, renderData);

console.log(output);

output was:

    <h1>test caption</h1>
    <p>test text</p>

So your template is fine. This implies that the problem is with your find function, or how you are handling the callback parameters.

If you are using mongo, this is likely because find returns a cursor, so you need to explicitly call the toArray function like this:

collection.find().toArray(function(err, documents) {

As per: https://mongodb.github.io/node-mongodb-native/api-generated/cursor.html

Sign up to request clarification or add additional context in comments.

1 Comment

@Maurice - Ok, if my answer was helpful I would appreciate it if you could 'accept' it. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.