0

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")
      }
    });
  }
});
3
  • 1
    You're setting it to true on line 6? Commented Apr 23, 2020 at 17:26
  • 2
    Is the function passed to Article.find(..) executed async ? Commented Apr 23, 2020 at 17:27
  • @David Was a typo, now edited Commented Apr 23, 2020 at 17:35

1 Answer 1

1

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")
      }
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Just added an query value, which maybe be better to filter what you are querying instead of getting all registers with find()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.