Reputation: 1
For some reason, my articleExists variable will not set to true on line 6, despite me using console logs to confirm that the if statement that it's contained in is triggering properly.
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")
}
});
}
});
Upvotes: 0
Views: 192
Reputation: 390
I believe this situation is probably caused by a misunderstanding regarding nodejs async nature.
I recommend you looking a bit into Promises and Async/Await, available at current nodejs versions, which made the code much cleaner and easier to understand.
This article seems to explain it pretty well: https://codeburst.io/javascript-es-2017-learn-async-await-by-example-48acc58bad65
Regarding your issue, here it goes an untested and not elegant solution, hope it helps you:
app.post("/articles", async (req, res) => {
const results = await Article.find(query);
const articleExists = results.some(result => result.title === req.body.title),
if (articleExists) {
return res.send("Article already exists!")
}
const newArticle = new Article({
title: req.body.title,
content: req.body.content
});
newArticle.save(err => {
if (err) {
return res.send(err);
} else {
return res.send("Article saved successfuly")
}
});
});
Upvotes: 1