Javascript 现有属性返回未定义
我使用node.js、express和mongodb启动了RESTful API的实现。到目前为止,一切都进展顺利,我有一个验证用户身份的方法,如下所示:Javascript 现有属性返回未定义,javascript,node.js,mongodb,express,undefined,Javascript,Node.js,Mongodb,Express,Undefined,我使用node.js、express和mongodb启动了RESTful API的实现。到目前为止,一切都进展顺利,我有一个验证用户身份的方法,如下所示: apiRoutes.post('/authenticate', function(req, res) { User.findOne({ nickname: req.body.nickname }, function(err, user) { if (err) throw err;
apiRoutes.post('/authenticate', function(req, res) {
User.findOne({
nickname: req.body.nickname
}, function(err, user) {
if (err) throw err;
if (!user) {
res.json({
success: false,
message: 'Authentication failed. User not found.'
});
} else if (user) {
console.log(user);
console.log(user.nickname);
console.log(user.email);
console.log(user.password);
console.log(user.sexe);
if (user.password != req.body.password) {
res.json({
success: false,
message: 'Authentication failed. Wrong password.'
});
} else {
var token = jwt.sign(user, app.get('salt'), {
expiresInMinutes: 1440 // expires in 24 hours
});
res.json({
success: true,
token: token
});
}
}
});
});
{ sexe: 'H',
email: 'MrPanda@gmail.com',
password: 'bambou',
nickname: 'MrPanda',
_id: 56cb703e7aef3f83c7dac0a7 }
检索用户,并在控制台中记录,如下所示:
apiRoutes.post('/authenticate', function(req, res) {
User.findOne({
nickname: req.body.nickname
}, function(err, user) {
if (err) throw err;
if (!user) {
res.json({
success: false,
message: 'Authentication failed. User not found.'
});
} else if (user) {
console.log(user);
console.log(user.nickname);
console.log(user.email);
console.log(user.password);
console.log(user.sexe);
if (user.password != req.body.password) {
res.json({
success: false,
message: 'Authentication failed. Wrong password.'
});
} else {
var token = jwt.sign(user, app.get('salt'), {
expiresInMinutes: 1440 // expires in 24 hours
});
res.json({
success: true,
token: token
});
}
}
});
});
{ sexe: 'H',
email: 'MrPanda@gmail.com',
password: 'bambou',
nickname: 'MrPanda',
_id: 56cb703e7aef3f83c7dac0a7 }
这很完美,但随后,以下三个consol.log返回以下三行:
MrPanda
MrPanda@gmail.com
undefined
H
我完全看不出为什么密码在这一点上是未定义的,我试图将属性名称更改为“mdp”,同样的问题。。。有什么想法吗?谢谢如果您使用的是
mongoose
它不会返回一个简单的JSON对象。它实际上是一个特殊的mongoose
对象,可能无法按您期望的方式运行
您有两个选择:
mongoose
对象转换为JSON
对象
- 将
添加到{lean:true}
选项参数用户
- 或
JSON.stringify(用户)
- 或
user.toJSON()
get()
和set()
方法(无论如何都应该这样做)
user.get('password')
user.get('email')
user.get('name')
试试看,如果它仍然不能工作,请告诉我。如果您使用的是
mongoose
,它会而不是返回一个简单的JSON对象。它实际上是一个特殊的mongoose
对象,可能无法按您期望的方式运行
您有两个选择:
mongoose
对象转换为JSON
对象
- 将
添加到{lean:true}
选项参数用户
- 或
JSON.stringify(用户)
- 或
user.toJSON()
get()
和set()
方法(无论如何都应该这样做)
user.get('password')
user.get('email')
user.get('name')
试试看,如果它仍然不能工作,请告诉我。尝试将user.password复制到新变量并记录它。尝试将user.password复制到新变量并记录它。