Mongoose更新:不接收回叫

vmdwslir  于 2023-03-08  发布在  Go
关注(0)|答案(1)|浏览(108)
app.get("/", function(req, res) {

  Item.find({}, function(err, foundItems) {

    if (foundItems.lengh === 0) {
      Item.insertMany(defaultItems, function(err) {
        if (err) {
          console.log(err);
        } else {
          console.log("Successfully saved default items");
        }
      });
      res.redirect("/");
    } else {
      res.render("list", {
        listTitle: "Today",
        newListItems: foundItems
      });

    }
  });

});

嘿,有谁知道如何更新这段代码,因为在mongoose 7中他们没有收到回调?

4smxwvx5

4smxwvx51#

可以使用promise代替回调

app.get("/", async (req,res)=>{

  try {
    const foundItems = await Item.find({})

    if(foundItems.length === 0) {

      await itMatchesOne.insertMany(defaultItems);

      res.redirect('/')

    }else{

      res.render('list', {
        listTitle: "Today",
        newListItems: foundItems
      })

    }
  } catch (error) {
    return res.status(400).send({ message:error.message });
  }

})

相关问题