【问题标题】:Cannot read property 'name' of undefined - mongoose, express, nodeJS, ejs无法读取未定义的属性“名称” - mongoose、express、nodeJS、ejs
【发布时间】:2021-05-24 22:34:39
【问题描述】:

如何从对象 ID 中获取用户名?我目前使用填充将用户数据从一个模式拉到另一个模式,它返回用户 ID 和名称,但我只想显示名称。我曾尝试在视图中使用 post.submittedby.name,但是我不断收到“名称未定义”错误。我也尝试将其设置为变量但同样的错误。

以下是我的数据在页面上的显示方式。

理想情况下,我想说发布者:user2

以下文件

后模型

const mongoose = require('mongoose');

const PostSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true,
    },
    date: {
        type: Date,
        default: Date.now,
        required: true,
    },
    submittedBy: {
        type: mongoose.Schema.Types.ObjectId, 
        ref: 'User',
    },
    comments: {
        type: String,
        default: 'Other info goes here',
    }
})

const Post = mongoose.model('Post', PostSchema);
module.exports = Post;

用户模型

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now
    }
});

const User = mongoose.model('User', UserSchema);
module.exports = User;

index.js

router.get('/dashboard', ensureAuthenticated, (req, res) => {
  Post.find()
    .populate({ path: 'submittedBy', select: 'name' })
    .then((result) => {
      res.render('dashboard', {
        posts: result,
        user: req.user,
      })
      
    })
    .catch((err) => {
      console.log(err)
    })

})

主页/仪表板视图.ejs

        <div class="forumView">
            <h2>All Posts</h2>

            <% if (posts.length > 0)  {%>
            <% posts.forEach(post => { %>

                <h3 class="title"> <%= post.title %></h3>
                <p class="body"> <%= post.body %> </p>
                <p class="body"> Posted by: <%= post.submittedBy %> </p>

            <% }) %>
            <% } else { %>
                <p>There are no posts to display...</p>  
                <% } %>  
        </div>

【问题讨论】:

    标签: node.js express mongoose ejs


    【解决方案1】:

    我认为当您将结果传递给模板时,那些submittedBy 子文档会被转换为字符串。所以试试这个:

    router.get('/dashboard', ensureAuthenticated, (req, res) => {
      Post.find()
        .populate({ path: 'submittedBy', select: 'name' })
        .lean() // <- This will give you plain JSON objects as opposed to mongoose docs.
        .then((result) => {
          result.forEach(i => i.submittedBy = i.submittedBy.name) // <- This will override the submittedBy prop with the actual name vs an object
          res.render('dashboard', {
            posts: result,
            user: req.user,
          })
          
        })
        .catch((err) => {
          console.log(err)
        })
    })
    

    此后,无需更改模板代码。

    免责声明:我没有对此进行测试。

    【讨论】:

    • 感谢您的回复!我尝试过这种方式并收到相同的错误 TypeError: Cannot read property 'name' of undefined 你会推荐另一种方法来为这些帖子提取用户名吗?我只使用填充,因为它是我看到的其他人推荐的
    • @kl 这次是在这一行得到的:results.forEach(i =&gt; i.submittedBy = i.submittedBy.name) 还是在 ejs 文件中得到的?你的 esj 文件应该仍然有这个 &lt;%= post.submittedBy %&gt;
    • 我在控制台上得到它,我的 ejs 文件甚至无法加载。
    • @kl 我的代码中有一个错字results.forEach(i =&gt;... 应该是result.forEach(i =&gt;...。你能确保那部分在你的代码中是正确的吗?
    • 是的,我发现并更改了它......似乎它仍然没有使用 .name 提交的
    猜你喜欢
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 2020-04-16
    • 2018-12-26
    • 1970-01-01
    相关资源
    最近更新 更多