'Unhandled promise rejection: TypeError: Cannot read property 'username' of undefined
I am pretty new to javascript and currently I am using MEAN stack for developing an application. I use the following code to find the username, friends' id and username of a particular user:
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);
});
});
}
And it always return the error:
(node:6044) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'friends' of undefined
Any help in this problem is greatly appreciated!
Edit: I changed the code as follow to get the err log:
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);
});
});
});
And the console log is:
{ 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
Solution 1:[1]
Just replace toArray with then.
userList.find({ "username": { $in: currUser.friends} }, { fields: {"username": true, "_id": true}}).toArray(function(err, friendList){
with
userList.find({ "username": { $in: currUser.friends} }, { fields: {"username": true, "_id": true}}).then(function(err, friendList){
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Manish Singh |
