简体   繁体   English

ZCCADCDEDB567ABAE643E15DCF0974E503Z 更新一个不存在的文档

[英]Mongoose updates a document which does not exists

I have a function that should update a token, based on an user's email.我有一个 function 应该根据用户的 email 更新令牌。 The thing is, the following code returns a token even if there isn't any document with the specified email in the mongoDB database and the function return the response code 200 to my server function. The thing is, the following code returns a token even if there isn't any document with the specified email in the mongoDB database and the function return the response code 200 to my server function. I'd like to prevent the updating of the document (and any further actions) when the specified e-mail isn't in the database or i'd like to return some information (regardless of the response code) to prevent further code from executing.当指定的电子邮件不在数据库中时,我想阻止更新文档(以及任何进一步的操作),或者我想返回一些信息(无论响应代码如何)以防止进一步的代码执行。

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

So after a series of trials & errors I finally figured out what's really wrong.因此,经过一系列的试验和错误,我终于弄清楚了真正的问题所在。 When I issued the query (whith an email which was not in any document) direcly into the mongoDB shell I got the following response:当我直接向 mongoDB shell 发出查询(其中 email 不在任何文档中)时,我得到以下响应:
{ "acknowledged": true, "matchedCount": 0, "modifiedCount": 0 }
The result clearly says that the wasn't any update ( modifiedCount is 0) but the query was still executing without any errors, so I had to "collect" that text and then continue the execution based on the "modifiedCount" value.结果清楚地表明没有任何更新(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);
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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