【问题标题】:Why get I this error message, if I want to read from the User collection the id property?如果我想从 User 集合中读取 id 属性,为什么会收到此错误消息?
【发布时间】:2020-11-26 09:15:31
【问题描述】:

app.js

app.get("/userid", function(req, res){
    User.findById(req.params._id, function(err, foundUser){
        if(err){
            res.redirect("/home");
        }else{
            res.render("userid", {User: foundUser});
        }
    });
});

userid.ejs

<%- include ("partials/header") %>
<h1>Userid List</h1>
<div class="container">
        <div class="row">
            <p><%= User._id %></p>
        </div>
</div>
<%- include ("partials/footer") %>

错误信息:

无法读取 null 的属性“_id”

如果我从终端检查 mongo,我可以看到,具有 id 属性的用户集合存在。 为什么会收到此错误消息?

感谢您的帮助

【问题讨论】:

  • 请在渲染命令上方使用console.log(foundUser)
  • @Mahesh Bhatnagar null
  • 所以这个错误来了Cannot read property '_id' of null
  • 因为我认为没有参数。请更改 app.get("/:userId) 的路径,注意 ":"。然后再次尝试记录 req.params。

标签: javascript mongodb express mongoose ejs


【解决方案1】:

解决办法如下:

//app.js

   app.get("/userid", function(req, res){
    User.find({}, function(err, foundUser){
        if(err){
            res.redirect("/home");
        }else{
            console.log(foundUser);
            res.render("userid", {User: foundUser});
        }
    });
   }); 

我使用了 find() 函数而不是 findById() 并且不再收到错误消息,但我在 userid.ejs 页面上看不到 id -> 添加了 forEach() 的迭代。

//userid.ejs

<%- include ("partials/header") %>
<h1>Userid List</h1>
<div class="container">
    <% User.forEach(function(User){ %>
        <div class="row">
            <p><%= User._id %></p>
        </div>
    <% }); %>
</div>
<%- include ("partials/footer") %>

现在一切正常! 有谁知道,为什么在这种情况下 findById() 不工作?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-22
    • 2021-08-10
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多