我正在根据其ID比较两个名为user和bloodrequest的文档,如果它们匹配,则在具有相同ID的表bloodrequest中显示值。我的问题是,我试图将当前登录的用户存储到这样的var中:var permit = mainUser.branch_id然后使用$where语句使用此代码:


  this.chapter_id == permit


这是我的代码,我唯一的问题是如何将MongoError: TypeError: mainUser is undefined :传递给mainUser.branch_id,我才刚刚开始学习

router.get('/bloodapprovedrequestmanagement', function(req, res) {
    User.find({}, function(err, users) {
        if (err) throw err;
        User.findOne({ username: req.decoded.username }, function(err, mainUser) {
            if (err) throw err;
            if (!mainUser) {
                res.json({ success: false, message: 'No user found' });
            } if (mainUser.branch_id === '111') {

                Bloodrequest.find({$where: function(err) {
                        var permit = mainUser.branch_id//gives me error here
                        return (this.request_status == "approved" && this.chapter_id == permit) }}, function(err, bloodrequests) {
                    if (err) throw err;
                    Bloodrequest.findOne({ patient_name: req.decoded.patient_name }, function(err, mainUser) {
                        if (err) throw err;
                        res.json({ success: true, bloodrequests: bloodrequests });
                    });
                });

            }
        });
    });
});

最佳答案

在本地范围之外声明变量。

 `router.get('/bloodapprovedrequestmanagement', function(req, res) {
           var permit;
            User.find({}, function(err, users) {
                if (err) throw err;
                User.findOne({ username: req.decoded.username }, function(err, mainUser) {
                    if (err) throw err;
                    if (!mainUser) {
                        res.json({ success: false, message: 'No user found' });
                    }
                    if(mainUser.branch_id === '111') {
                        permit = mainUser.branch_id;
                        Bloodrequest.find({$where: function(err) {
                            return (this.request_status == "approved" && this.chapter_id == permit) }}, function(err, bloodrequests) {
                            if (err) throw err;
                            Bloodrequest.findOne({ patient_name: req.decoded.patient_name }, function(err, mainUser) {
                                if (err) throw err;
                                res.json({ success: true, bloodrequests: bloodrequests });
                            });
                        });

                    }
                });
            });
        });`

关于javascript - 如何从另一个函数将值存储到var,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53627196/

10-12 12:58
查看更多