我是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
答案 0 :(得分:0)
用那时替换toArray。
userList.find({ "username": { $in: currUser.friends} }, { fields: {"username": true, "_id": true}}).toArray(function(err, friendList){
与
userList.find({ "username": { $in: currUser.friends} }, { fields: {"username": true, "_id": true}}).then(function(err, friendList){