简体   繁体   English

猫鼬查找,执行逻辑,然后在同一集合上进行更新

[英]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: 我有一个使用findOneAndUpdate完成的解决方案,并且如果返回的记录为0,我将返回错误状态,但是我很好奇理解以下原因为何不起作用:

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: 特别是在find.then内的Users.update时,总是返回num:

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

Which means that no records were found although the record was indeed found with the first findOne. 这意味着尽管确实在第一个findOne中找到了记录,但未找到任何记录。

EDIT: more information about the libraries, as maybe it's a matter of updating them (from package.json): 编辑:有关库的更多信息,因为可能是更新它们的问题(来自package.json):

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

Thanks, T. 谢谢,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 您必须在findOne使用(err,output)

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(....;

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

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