【问题标题】:Mongoose updates a document which does not existsMongoose 更新一个不存在的文档
【发布时间】:2021-03-10 08:24:14
【问题描述】:

我有一个函数应该根据用户的电子邮件更新令牌。问题是,即使 mongoDB 数据库中没有任何带有指定电子邮件的文档,以下代码也会返回一个令牌,并且该函数将响应代码 200 返回到我的服务器函数。当指定的电子邮件不在数据库中时,我想阻止更新文档(以及任何进一步的操作),或者我想返回一些信息(无论响应代码如何)以防止进一步的代码正在执行。

const vnosZetona = (req,res) =>{
    if(!req.body.ePosta ){
        return res.status(400).json({
            "sporočilo": "Epošta uporabnika manjka! Parameter je obvezen"
        });
    }
    if(!(new RegExp("[a-z]{2}[0-9]{4}@student.uni-lj.si").test(req.body.ePosta))){
        return res.status(400).json({
            "sporočilo": "Izgleda da nisi študent UL! Hm, "
        });
    }
    var generiranZeton = generirajObnovitveniZeton();
    User
    .updateOne( {email: req.body.ePosta},
                { $set: {zetonZaObnavljanjeGesla:generiranZeton}},
                (napaka) => {
                    if(napaka){
                       return res.status(400).json(napaka);
                    }else{
                        return res.status(200).json({
                            zeton : generiranZeton,
                            "sporočilo" : "Žeton uspešno dodan."
                        });
                    }         
                }
    )
  
  };

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    因此,经过一系列的尝试和错误,我终于弄清楚了真正的问题所在。当我直接向 mongoDB shell 发出查询(带有一封不在任何文档中的电子邮件)时,我得到了以下响应:
    { "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }
    结果清楚地表明没有任何更新(modifiedCount 为 0),但查询仍在执行而没有任何错误,因此我必须“收集”该文本,然后根据“modifiedCount”值继续执行。

    const vnosZetona = (req,res) =>{
         //check for errors and other stuff
        var generiranZeton = generirajObnovitveniZeton(); //generate random token
         User
        .updateOne( {email: req.body.ePosta},
                    { $set: {zetonZaObnavljanjeGesla:generiranZeton}},
                    (napaka, sporociloQueryja) => {
                        if(napaka){
                           return res.status(400).json(napaka);
                        }else{
                            return res.status(200).json({
                                zeton : generiranZeton,
                                status: JSON.stringify(sporociloQueryja),
                                //the field "status" returns the result mentioned above 
                                //although slightly different than  in the mongoDB shell:
                                //{"n":0,"nModified":0,"ok":1}
                                "sporočilo" : "Žeton uspešno dodan."
                            });
                        }         
                    }
        );
        
      };
    
    //The following code calls the API above when we complete the form on the page and hit submit
    const posljiZahtevoZaObnovoGesla = async (req,res,next) =>{
        
        //check for a valid email address 
       
        try{
            let odgovor = await axios.put(apiParametri.streznik + "/api/uporabniki/vnosZetona",{
                ePosta : req.body.ePosta
            });
    
            if(odgovor.status == 200){
               
                //If the query had no errors,regardless if anything was updated
                // we read the data that was returned from the API -> 
                // with a nonexistent mail, the  "odgovor.data.status" equals "{"n":0,"nModified":0,"ok":1}"
                var o = JSON.parse(odgovor.data.status);
            
                if(o.nModified == 0){
                    //nothing was modified, the no document with the specified email exists
                    // the user gets redirected to registration form
                    return res.redirect("/registracija");
                }
                //the code sends the instructions to the specified mail that exists in database
                //using nodemailer and redirects to user sign in
                res.redirect("/prijava");
            }
            else if (odgovor.status >= 400){
                res.status(odgovor.status).json(
                    {"sporocilo": "Nekaj si zafrknil! Rollbackaj na začetno stanje!"}
                );
              
            }
        }catch(napaka){
            next(napaka);
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-05
      • 2011-12-07
      • 2015-02-19
      • 2021-10-23
      • 2015-10-04
      • 2015-02-09
      • 2021-09-12
      • 1970-01-01
      相关资源
      最近更新 更多