未处理的承诺拒绝:类型错误:无法读取未定义的属性“用户名”

问题描述 投票:0回答:1

我对 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
javascript node.js mongodb
1个回答
0
投票

只需将 toArray 替换为 then 即可。

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){
© www.soinside.com 2019 - 2024. All rights reserved.