简体   繁体   中英

Cannot read property of undefined - NodeJS, Express, Mongoose

I got this two functions

exports.list = function (req, res){
Material.find(function(err, materials) {
    res.render('materials/list', {title: 'Pagina Materiali', materials: materials});
});
}

exports.modify = function (req, res){
Material.findById(req.params.id, function(err, materials){
    res.render('materials/edit', {title: 'Pagina materiale singolo', materials: materials});
});
}

The first one works properly and I cycle it with this Jade snippet:

each material in materials
    p Nome materiale: #{material.m_name} | Tipo materiale: #{material.type} | 
     a(href='materials/edit/#{material.id}') Modifica Materiale

But I can't get the second one to work and Express tell me that it cannot read properties of an undefined. If I view the result in the console or just return it I can see that it's picking the right value, it's just that I'm not able to show it properly in the template. Any help? Thanks!

findById finds a single document by id. You trying to each it as array of objects.

You need something like this in node:

Material.findById(req.params.id, function(err, material){
    res.render('materials/edit', {title: 'Pagina materiale singolo', material: material});
});

In jade:

p Nome materiale: #{material.m_name} | Tipo materiale: #{material.type} | 
  a(href='materials/edit/#{material.id}') Modifica Materiale

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM