【问题标题】:Mongodb will not create document within if/else statementMongodb 不会在 if/else 语句中创建文档
【发布时间】:2020-02-11 03:42:19
【问题描述】:

MongoDB 新手。仅当该集合中不存在同名文档时,我才尝试将新文档添加到现有集合中。我首先使用 if/else 语句来检查是否存在与新条目同名的文档,如果没有,则使用 else 语句来创建新条目。无论我尝试什么,都不会添加新文档,而是返回一个空数组。如有任何帮助,我将不胜感激。

我尝试过切换 if/else 语句;在 if 语句返回时检查 null 和 undefined 值

app.post('/cocktails/new', isLoggedIn, (req, res) => {
// add to DB then show item
    let name = req.body.name;
    let style = req.body.style;
    let spirit = req.body.spirit;
    let image = req.body.image;
    let description = req.body.description;
    let newCocktail = {name: name, style: style, base: spirit, image: 
    image, description: description}
    Cocktail.find({name}, function (err, existCocktail) {
        if(existCocktail){
            console.log(existCocktail)
}
 else {Cocktail.create(newCocktail, (err, cocktail) => {
console.log(cocktail)
if (err) {console.log(err)}
else {
res.redirect('/cocktails/' + cocktail._id)}
})

        }
    })
})

如果使用 if 函数找不到事件文档,则会执行 else 语句,从而使用 newCocktail 对象创建新文档。

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    你应该使用 findOne 而不是 find。

    当没有找到文档时,find 返回一个空数组。

    下面的表达式返回真,所以你的existCocktail条件为真,导致你的新数据没有添加。

    [] ? true : false
    

    我还稍微重构了你的代码,你可以使用解构你的 req.body。

    app.post("/cocktails/new", isLoggedIn, (req, res) => {
      // add to DB then show item
    
      const { name, style, spirit, image, description } = red.body;
    
      let newCocktail = {
        name,
        style,
        base: spirit,
        image,
        description
      };
      Cocktail.findOne({ name }, function(err, existCocktail) {
        if (existCocktail) {
          console.log(existCocktail);
          res.status(400).json({ error: "Name already exists" });
        } else {
          Cocktail.create(newCocktail, (err, cocktail) => {
            console.log(cocktail);
            if (err) {
              console.log(err);
              res.status(500).json({ error: "Something went bad" });
            } else {
              res.redirect("/cocktails/" + cocktail._id);
            }
          });
        }
      });
    });
    

    【讨论】:

    • 成功了。谢谢!知道 FindOne 为何有效但 Find 无效的原因吗?
    • @monkeytrick 很高兴听到它,你能接受作为答案吗?
    • @monkeytrick Find 总是返回 smth。如果没有找到它会返回一个空列表。所以检查“existCocktail”总是正确的。
    • @S.Kuiter 谢谢你,我会把这个添加到答案中。
    • @monkeytrick 我通过编辑答案解释了 find 的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多