为什么可以';我不能将javascript变量设置为false吗?
出于某种原因,尽管我使用控制台日志确认它所包含的if语句正确触发,但我的articleExists变量在第6行上不会设置为true为什么可以';我不能将javascript变量设置为false吗?,javascript,variables,boolean,Javascript,Variables,Boolean,出于某种原因,尽管我使用控制台日志确认它所包含的if语句正确触发,但我的articleExists变量在第6行上不会设置为true app.post("/articles", function(req, res) { let articleExists = (false); Article.find(function(err, results) { results.forEach(function(result) { if (result.title === req.
app.post("/articles", function(req, res) {
let articleExists = (false);
Article.find(function(err, results) {
results.forEach(function(result) {
if (result.title === req.body.title) {
articleExists = (true);
}
});
});
if (articleExists) {
res.send("Article already exists!")
} else {
const newArticle = new Article({
title: req.body.title,
content: req.body.content
});
newArticle.save(function(err) {
if (err) {
res.send(err);
} else {
res.send("Article saved successfuly")
}
});
}
});
我相信这种情况可能是由于对nodejs异步性质的误解造成的 我建议您仔细研究一下Promissions和Async/Await,它们在当前的nodejs版本中可用,这使代码更清晰、更容易理解 这篇文章似乎很好地解释了这一点: 关于您的问题,这里有一个未经测试且不优雅的解决方案,希望它能帮助您:
app.post(“/articles”),异步(req,res)=>{
const results=wait Article.find(查询);
const articleExists=results.some(result=>result.title===req.body.title),
如果(存在){
return res.send(“文章已存在!”)
}
const newArticle=新文章({
标题:req.body.title,
内容:req.body.content
});
newArticle.save(错误=>{
如果(错误){
返回res.send(err);
}否则{
return res.send(“物品成功保存”)
}
});
});
您正在第6行将其设置为true
吗?函数是否传递给文章。查找(…)
异步执行?@David是一个打字错误,现在编辑刚刚添加了一个query
值,这可能比使用find()获取所有寄存器更好