对象值未定义:MEAN Stack
Object value is undefined : MEAN Stack
这是我的代码
//to check whether email exist or not
router.post('/forgot', function(req,res) {
User.find({email: req.body.email}, function(err,found) {
console.log('finding email');
if(found.length) {
//console.log(found);
resets(found);
return res.json({success: true, msg: 'User found'});
//return res.json(found);
}
else if(err) {
return res.json({success: false, msg: 'User not found'});
}
else if(!found) {
return res.json({success: false, msg: 'User not found'});
}
});
});
function resets(foundData) {
console.log(foundData.email);
var mailObj = foundData.email;
console.log(mailObj);
}
在我的控制台中,我得到的输出是
finding email undefined
undefined
但是当我试图只显示 foundData
对象时,我在控制台中得到的输出是
finding email
[ { _id: 5b3ca69ba87aa42414993682,
name: 'xxxxx',
email: 'xxx',
username: 'xxxxx',
password: 'a$ZLeRJvizxk62EOS/5mZT6evz7.mFbzf38K6pAzr69O/5I2EZ6WJWO',
phone: '',
location: '',
title: '',
company: '',
education: '',
__v: 0 } ]
这是上述输出的代码。
function resets(foundData) {
console.log(foundData);
}
我想要 foundData
对象中的变量 email
。我该如何解决这个问题?
那是因为您正在尝试访问一个不存在的对象 属性。
在您记录的对象中,您有一个数组,内部有一个对象。那是因为 MongoDB
查找方法试图找到 每个对象 匹配条件,如果你只想要一个对象,你应该使用类似 findOne
的方法。
试试这个:
var mailObj = foundData[0].email;
这是我的代码
//to check whether email exist or not
router.post('/forgot', function(req,res) {
User.find({email: req.body.email}, function(err,found) {
console.log('finding email');
if(found.length) {
//console.log(found);
resets(found);
return res.json({success: true, msg: 'User found'});
//return res.json(found);
}
else if(err) {
return res.json({success: false, msg: 'User not found'});
}
else if(!found) {
return res.json({success: false, msg: 'User not found'});
}
});
});
function resets(foundData) {
console.log(foundData.email);
var mailObj = foundData.email;
console.log(mailObj);
}
在我的控制台中,我得到的输出是
finding email undefined undefined
但是当我试图只显示 foundData
对象时,我在控制台中得到的输出是
finding email
[ { _id: 5b3ca69ba87aa42414993682,
name: 'xxxxx',
email: 'xxx',
username: 'xxxxx',
password: 'a$ZLeRJvizxk62EOS/5mZT6evz7.mFbzf38K6pAzr69O/5I2EZ6WJWO',
phone: '',
location: '',
title: '',
company: '',
education: '',
__v: 0 } ]
这是上述输出的代码。
function resets(foundData) {
console.log(foundData);
}
我想要 foundData
对象中的变量 email
。我该如何解决这个问题?
那是因为您正在尝试访问一个不存在的对象 属性。
在您记录的对象中,您有一个数组,内部有一个对象。那是因为 MongoDB
查找方法试图找到 每个对象 匹配条件,如果你只想要一个对象,你应该使用类似 findOne
的方法。
试试这个:
var mailObj = foundData[0].email;