【问题标题】:Display Mongo user data in EJS file with node/express使用 node/express 在 EJS 文件中显示 Mongo 用户数据
【发布时间】:2022-01-04 05:25:02
【问题描述】:

我正在运行 node/express/mongoose/mongo 并尝试在其帐户页面中显示已登录用户的信息。

在我的用户控制器文件中,我试图访问他们的 Mongo 用户 ID,然后查找完整的用户对象,将该对象加载到 const 中,并将该对象传递到 EJS 文件的渲染中。

const User = require('../models/user');

module.exports.account = async (req, res) => {
    const userID = req.user._id;
    const { user } = await User.findById(userID);
    res.render('app/account', { user })
}

当我 console.log 用户 ID 时,我得到“new ObjectId("61d321284256dffb7e869e8f")”(我不应该只得到数字字符串吗?)。 当我在硬编码 findByID('61d321284256dffb7e869e8f') 时 console.log user.email 时,我收到错误“TypeError: Cannot read properties of undefined”。

真的迷路了,所以我很感激这里的任何帮助。

【问题讨论】:

  • req 变量及其值是什么?
  • req.user._id 是从护照 (passportjs.org) 中检索到的。当我 console.log(req.user._id) 我得到 new ObjectId("61d321284256dffb7e869e8f") 但我只想要字符串,不知道如何解析它。
  • 我认为有一个toString() 函数(或类似的东西)来获取 string 值。

标签: node.js mongodb express mongoose ejs


【解决方案1】:

已回答-在代码中添加了toString,还发现我用过,

module.exports.account = async (req, res) => {
    const userID = req.user._id.toString();
    const user = await User.findById(userID);
    res.render('app/account', { user })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 2013-07-19
    • 2021-07-28
    • 2016-12-15
    相关资源
    最近更新 更多