首页 > 解决方案 > save() 被调用一次,但在猫鼬中第一次被执行两次

问题描述

我正在创建一个待办事项列表,该列表在 url 上更改参数时动态创建一个列表。如果该列表已经存在,它会呈现该列表并且不会再次创建。但是,当我运行代码并给它一个随机路由时,它基本上执行 list.save() 两次,但只是第一次。从第二次开始,它运行正常。怎么了?

app.get("/:customListName", function (req, res) {
    const customListName = req.params.customListName;

    List.findOne({ name: customListName }, function (err, foundList) {
        if (!err) {
            if (!foundList) {
                const list = new List({
                    name: customListName,
                    items: defaultItems
                })
                list.save();

                res.redirect("/" + customListName);
            } else {
                res.render('list', { aajakoDay: foundList.name, listItems: foundList.items })
            }
        }
    })
}) 

在此处输入图像描述

标签: node.jsmongodbexpressmongoose

解决方案


我认为重定向是导致问题的原因

res.redirect("/" + customListName); 

list.save() 本身似乎是异步函数。因此,您在实际保存之前重定向它。现在,当它被重定向时,它仍然没有找到(尚未保存到 DB)并且 save() 再次执行。

如果可能的话(传递另一个回调函数),将响应部分移动到 save() 函数中,或者使用 await 等待其保存,然后进行重定向。

另一种方法是重定向到“/”或主页。

您还可以使用 async-await 功能来解决 Promise 并使代码更加干净和高效。

app.get("/:customListName",async function(req,res){
     try{
         const customListName = req.params.customListName;
         let listItem = await List.findOne({ name: customListName });
         //if listitem is found in db
         if(listItem){
             return res.render('list',{ aajakoDay: foundList.name, 
             listItems: foundList.items })
         }
         else{
             //create the listItem
             let newListItem = await List.create({name:customListName, items:defaultItems});
             await newListItem.save();
             return res.redirect("/" + customListName);
         } 
     }catch(err){
         console.log("Error: ",err);
         return; 
     }
});

你可以参考这篇博客:https ://blog.risingstack.com/mastering-async-await-in-nodejs/


推荐阅读