简体   繁体   中英

Why can't I set my javascript variable to false?

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")
      }
    });
  }
});

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")
      }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM