【发布时间】: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