【发布时间】:2021-03-13 21:19:14
【问题描述】:
我的 MongoDB 中有这个文档
{
_id: 603e59811a640a0d1097bc35,
firstName: 'ABC',
lastName: 'XYZ',
address: 'Mars',
age: 20,
mobile: 9922334455,
email: 'abc@gmail.com',
password: 'pass',
type: 'citizen',
__v: 0
}
下面是我用来获取它的代码:
router.post('/login', (req, res) => {
const user = new User({
userName: req.body.userName,
password: req.body.password,
})
User.findOne(
{
email: user.userName,
password: user.password,
},
(err, data) => {
console.log(data)
}
)
})
在控制台中我得到的输出是:
{
_id: 603e59811a640a0d1097bc35,
firstName: 'ABC',
lastName: 'XYZ',
address: 'Mars',
age: 20,
mobile: 9922334455,
email: 'abc@gmail.com',
password: 'pass',
type: 'citizen',
__v: 0
}
现在,当我尝试访问console.log(data.firstName) 之类的数据时,它显示我为undefined。但是如果我做console.log(data._id) 这是第一个属性的键,它会给出正确的值,即603e59811a640a0d1097bc35
更新
我尝试调试并发现: enter image description here
result 的数据类型是model。如果我使用${result._doc.firstName},它会给我名字。但这是访问属性的正确方法吗?
【问题讨论】:
-
您是否将密码以明文形式存储在数据库中?您应该永远不要这样做,而是存储哈希值!
-
我正在学习node和MongoDB。稍后会这样做。你对我提出的问题有解决方案吗?
-
你写
console.log(data.firstName)的地方和console.log(data)完全一样吗? -
@t.niese 是的,我做到了。
标签: javascript node.js json mongodb crud