简体   繁体   中英

Mongoose find, execute logic, then update on the same collection

I need to find a document, check some condition on its fields and perform an action or another depending on the outcome of a condition. This is inside a request handling so I must return different things in the response depending on the outcomes.

I have a solution done with findOneAndUpdate and if the returned records are 0 I return an error status, but I am curious to understand why the following doesn't work:

Users.findOne({'username':someVariable}).then((output)=>{

     if(output.someFiled > someCondition){
          Users.update(
              {'username':someVariable},
              {$set: {....}}
          ).then((error, num, success) =>{
              if(success){
                  return res.status(200).send('UPDATE OK');
              }
              if(error){
                  return res.status(500).....;
              }
          });
     } else {
         return res.status(404).....;
     }        

}).catch(....;

In particular the Users.update inside the find.then always return num:

{ ok: 0, n: 0, nModified: 0 }

Which means that no records were found although the record was indeed found with the first findOne.

EDIT: more information about the libraries, as maybe it's a matter of updating them (from package.json):

"bluebird": "^3.4.6",
"mongodb": "^3.0.2",
"mongoose": "^4.12.4",

Thanks, T.

Found the problem: the model file of the User didn't have the fields I was trying to update. The "find" part works also if the model has no declaration of such fields, but the "update" part won't.

So yea, just like that, should have read all the code but I thought it was boring.. never lucky.

you have to use (err,output) in findOne

Users.findOne({'username':someVariable}).then((err,output)=>{

     if(output.someFiled > someCondition){
          Users.update(
              {'username':someVariable},
              {$set: {....}}
          ).then((error, num, success) =>{
              if(success){
                  return res.status(200).send('UPDATE OK');
              }
              if(error){
                  return res.status(500).....;
              }
          });
     } else {
         return res.status(404).....;
     }        

}).catch(....;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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