gpt4 book ai didi

node.js - NodeJS MongoDB 回调 hell

转载 作者:太空宇宙 更新时间:2023-11-03 23:37:00 24 4
gpt4 key购买 nike

我在条件和数据库回调方面仍然遇到问题,我编写了一个查询违规对象的路由函数,这是来自客户端填写的表单。我正在尝试更改拥有此违规行为的用户作为一个选项,我查询该用户并返回它,但是在 if 语句中, x != y 将始终返回 true,因为我编写此代码的性质。我希望它完成查询,然后点击条件。我对如何解决这个问题感到有点困惑。

 if(viol.user != user[0]._id)

这样,当我编辑拥有该违规或对象的用户时,该用户就不会一遍又一遍地向自身添加相同的对象。

app.post('/singleViolation/:violation', isAdmin, function(req, res) {
var violation = req.params.violation;


Violation.findById(violation, function(err, viol){
if (err) throw err;
if (req.body.cause === '') {
req.body.cause = viol.cause;
}
if (req.body.date === '') {
req.body.date = viol.date;
}
if (req.body.location === '') {
req.body.location = viol.location;
}


if(req.body.email === '') {
req.body.email == viol.user;
}

if( req.body.email != '') {

User.find({"local.email" : req.body.email}, function (err, user) {


if (err) {
req.body.email = viol.user;
}

if(viol.user != user[0]._id) {
typeof viol.user;
typeof user[0].id;
console.log(viol.user);
console.log(user[0]._id);
console.log(viol.user === user[0].id);
viol.user = user[0];
viol.save();

user[0].local.violations.push(viol);
Vehicles.findById(viol.vehicle, function(err, veh) {

user[0].local.vehicles.push(veh);
veh.owner = user[0];
veh.save();
user[0].save();

});

}
});
}

viol.cause = req.body.cause;
viol.date = req.body.date;
viol.location = req.body.location;

viol.save();

});
res.json(req.body);
});
app.get('/editViolations/:violations', isAdmin, function(req, res) {
res.render('editViolations.ejs');
});

最佳答案

您需要使用事件来实现您想要的。下面只是一个高级解决方案。

  • 查询完成时触发事件。
  • 将上述事件与您的条件语句相关联。
  • 当满足所需条件时触发另一个事件。
  • 将此事件与您的返回声明相关联。

阅读this很好的 tutplus 博客,让您了解 Node event module .

关于node.js - NodeJS MongoDB 回调 hell ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30892799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com