【发布时间】:2016-12-14 05:18:49
【问题描述】:
我对 javascript 很陌生,目前我正在使用 MEAN 堆栈来开发应用程序。我使用以下代码来查找特定用户的用户名、朋友的 id 和用户名:
router.get('/init', function(req, res) {
var db = req.db;
var userList = db.get('userList');
//get username & friends
userList.findOne({ "_id" : ObjectId("584d576ef0000ef5a94706f5") },{ fields: { "username": true, "_id": false, "friends":true } }, function(err, currUser){
userList.find({ "username": { $in: currUser.friends} }, { fields: {"username": true, "_id": true}}).toArray(function(err, friendList){
// Generate response
var response = {
"username": currUser.username,
"friends": friendList
};
res.json(response);
});
});
}
而且它总是返回错误:
(node:6044) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'friends' of undefined
非常感谢您对此问题的任何帮助!
编辑: 我将代码更改如下以获取错误日志:
router.get('/init', function(req, res) {
var db = req.db;
var userList = db.get('userList');
//var username, friends;
userList.findOne({ "_id" : ObjectId("584d576ef0000ef5a94706f5") },{ fields: { "username": true, "_id": false, "friends":true } }, function(err, currUser){
console.log(currUser);
if(err) console.log("findOne: "+err);
userList.find({ "username": { $in: currUser.friends} }, { fields: {"username": true, "_id": true}}).toArray(function(err, friendList){
// Generate response
if(err) console.log("find: "+err);
var response = {
"username": currUser.username,
"friends": friendList
};
res.json(response);
});
});
});
而控制台日志是:
{ username: 'Eddie', friends: [ 'Ken', 'Alice', 'Bill' ] }
undefined
findOne: TypeError: userList.find(...).toArray is not a function
(node:8888) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'friends' of undefined
【问题讨论】:
-
你确定 userList.findOne 返回一个有效的
currUser? -
是的,该部分返回一个有效的 currUser。
-
TypeError: Cannot read property 'username' of undefined表明代码正在从undefined对象访问属性username。这可能是在您的currUser.username的情况下,如果 currUser 未定义 -
console.log(err)在每次userList.find()通话中记录到console的内容是什么?userList.find()是否返回Promise?您是否在javascript中包含.then()、.catch()? -
感谢您的回复。我已将错误日志添加到问题中。抱歉,我不熟悉
Promise的概念...有什么方法可以检查Promise是否返回?
标签: javascript node.js mongodb