我正在根据自己的ID比较名为user和bloodrequest的两个文档,如果它们匹配,则在具有相同ID的表bloodrequest中显示值。我的问题是,我试图将当前登录的用户存储到这样的var中:var permit = mainUser.branch_id
,然后使用$where
语句,使用此语句:this.chapter_id == permit
,但给我错误。 / p>
MongoError: TypeError: mainUser is undefined :
这是我的代码,我唯一的问题是如何将mainUser.branch_id
传递给var permit
,我才刚刚开始学习
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 });
});
});
}
});
});
});
答案 0 :(得分:0)
在本地范围之外声明变量。
`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 });
});
});
}
});
});
});`
答案 1 :(得分:0)
将您的callback
转换为async await
更加简单。
router.get('/bloodapprovedrequestmanagement', function async(req, res) {
try {
var permit;
let mainUser = await User.findOne({ username: req.decoded.username });
if(mainUser && mainUser.branch_id && mainUser.branch_id === '111') {
permit = mainUser.branch_id;
// here you add your condiion for (this.request_status == "approved" && this.chapter_id == permit).
let bloodRequestData = await Bloodrequest.findOne({ patient_name: req.decoded.patient_name });
res.json({ success: true, bloodrequests: bloodRequestData });
}
} catch (error) {
throw error
}
}
据我了解,您尚未在代码中使用
User.find({})
和Bloodrequest.find({})
数据。