Home > database >  NODEJS Include variable from POST
NODEJS Include variable from POST

Time:10-17

Hi I want to display information from array brought from database into a ejs/html page, and I'm getting a 'is not defined' error...

Error I'm getting /CLICK TO SEE PICTURE

Then I have a POST method displaying in console all that is in array such as:

  app.post('/quotes', (req, res) => {
  datacollection.insertOne(req.body)
    .then(result => {
      console.log(result)
      res.redirect('/quotes')
      db.collection('datacollection').find().toArray()
    .then(results => {
      console.log(results)
    })
    .catch(error => console.error(error))
  // ...
    })
    .catch(error => console.error(error))
});

and on the html/ejs page I have a include that is:

'<%= datacollection %>'

I am trying to pass the value via:

app.get('/quotes', (req, res) => {
  db.collection('datacollection').find().toArray()
    .then(results => {
      res.render('quotes.ejs', { datacollection: results })
    })
    .catch(/* ... */)

})

how do I make it work?

CodePudding user response:

Hi first in your get request you should type

res.render("quotes")

instead of

res.render("quotes.ejs")

which is wrong.

I assume that in your code you have public directory and views directory ,in order to work properly and your code be able to see them.As you are working in a database like mongo in post request you must save new result and then redirect to a route

result.save();
res.redirect("/");

In get request try this

*your_db_model*.find({"result": {$ne: null}}, function(err, results){
      if (results) {
        res.render("quotes", {datacollection: results});
      }

Also you have array so you must print it in quote.ejs like this

<%  datacollection.forEach(function(data){ %>

    <h1><%=data.title%></h1>
<% } %>

I hope this will help you find some of the errors in your code.Send again if your code still not works.

  • Related