无法读取null的属性“ _id”

时间:2018-12-20 15:13:27

标签: node.js mongodb ejs

我收到此错误:

  

TypeError:   /home/application/projetnode/projetnode/views/problemes/edit.ejs:5       3 |编辑问题       4 |

     
    
      

5 | /problemes/<%=probleme._id%>?_ method = PUT“ method =” POST“>           6 |           7 |
          8 |

    
  
     

无法读取null的属性“ _id”

查看有问题的ejs

<% include ../partials/header %>
    <div class="row">
        <h1 style="text-align: center">Edit Problem</h1>
        <div style="width: 30%; margin: 25px auto;">
            <form action="/projets/<%= projet_id %>/problemes/<%=probleme._id %>?_method=PUT" method="POST">
                <div class="form-group">

                </div>
                <div class="form-group">
                    <button class="btn btn-lg btn-danger btn-block">Submit!</button>
                </div>
            </form>
        </div>
    </div>
<% include ../partials/footer %>

编辑路线

  router.get("/:problemeId/edit", middleware.isLoggedIn, function(req, res){
        // find probleme by id
        Projet.findById(req.params.problemeId, function(err, probleme){
            if(err){
                console.log(err);
            } else {
                 res.render("problemes/edit", {projet_id: req.params.id, probleme: probleme});
            }
        })
    });

// route put

router.put("/:problemeId", function(req, res){
   Probleme.findByIdAndUpdate(req.params.problemeId, req.body.probleme, function(err, probleme){
       if(err){
          console.log(err);
           res.render("edit");
       } else {
           res.redirect("/projets/" + req.params.id);
       }
   }); 
});

2 个答案:

答案 0 :(得分:0)

从错误消息中:

Cannot read property '_id' of null

似乎probleme == null中的probleme._id。使用problemeId或将对象probleme设置为非null。

答案 1 :(得分:0)

router.get("/:problemeId/edit", middleware.isLoggedIn, function(req, res){
        // find probleme by id
        Projet.findById(req.params.problemeId, function(err, probleme){
            if(err){
                console.log(err);
            } else {
                 res.render("problemes/edit", {projet_id: req.params.problemeId, probleme: probleme});
            }
        })
    });

您正试图在编辑路径中获得projet_id: req.params.id,但是在获取路径中您已取消了router.put("/:problemeId", function(req, res)的名称,因此您已将req.params.id更改为req.params.problemeId