There is a collection of sights , a sight collection is embedded in it, which has a titleSight field. The problem with the output value of titleSight in the template. Gives the error: Cannot read property 'titleSight' of undefined . How to display the value of the titleSight field?

route.js

  app.get('/sight-overall/:id', function (req, res) { Promise.all([ Photo.find({}), Sight.find({_id: req.params.id}) ]).then(function (data) { console.log('data:', data); res.render('sight-overall.ejs', {photoList: data[0], sights: data[1], isAuth: req.isAuthenticated()}); }); 

sights-overall.ejs

  <% var sights = JSON.stringify(sights) %> <% if (locals.sights) { %> <div class="sight-overall__header"> <h2><%= sights.sight.titleSight%></h2> </div> <% } %> 

data content:

enter image description here

DB content: enter image description here

  • <% var sights = JSON.stringify(sights) %> , make such a variable in ejs, and work with it. - uber42
  • @ uber42, but what's my mistake you can't see? Just did the same for other models. There were no problems - vita_run
  • even helped you? - uber42
  • @ uber42, displays the same error. Corrected a post, can not understand you so? - vita_run
  • one
    <%= sights[0].sight.titleSight%> add the index - uber42

1 answer 1

The template engine tries to create a string from your object, so you get this result.


Take, for example, such an object:

 sights = { sight : { title : "title" } } 

And pass to our template:

 res.render('index', { data: sights }); 

Our object falls into place in ejs as a string so we get a similar result: [object Object] with <%= data %> .

But if during templating we wrap the string data (which was originally an object) in JSON.stringify, then our string will become an object back. This way we get: {"sight":{"title":"title"}} with <%= JSON.stringify(data) %>