【问题标题】:mongoose findOne, update and exec猫鼬 findOne,更新和执行
【发布时间】:2015-04-05 00:12:32
【问题描述】:

我很困惑如何根据following documentation 使用 mongoose 使用 findOne().update().exec() 应该返回一个承诺,但返回的内容没有失败成员:

var ret = mongoose.models[collection].findOne({_id:id})
      .update({status:status})
      .exec();
console.log('having fail:',ret.fail);//undefined
console.log('having catch:',ret.catch);//undefined
console.log('having then:',ret.then);//this is defined

这可能是因为他们的承诺没有实现失败或捕获,我必须尝试在最后一个 .then 上设置一个拒绝函数,看看是否会被调用:

promise.then(returningPromise)
  .then(returningPromise)
  .then(returningPromise)
  .then(null,handleFail)

然后我尝试以下方法:

var ret = mongoose.models[collection].findOne({_id:id})
//      .update({status:status})
        .exec(function(er,dt){
          //callback: null { _id: 000000000000000000000001,...
          console.log('callback:',er,dt);
      });

很高兴看到我得到了一些东西,但取消注释更新,我得到以下内容:

var ret = mongoose.models[collection].findOne({_id:id})
        .update({status:status})
        .exec(function(er,dt){
          //callback: null null
          console.log('callback:',er,dt);
      });

记录也没有更新。我知道如果没有找到记录但没有更新它确实找到了记录。

所以我的主要问题是如何使用 findOne 和 update(而不是 findOneAndUpdate)更新此记录,第二个问题是如果第一个 promise 拒绝,是否会调用最后一个 .then 的拒绝。如果不是,那么由于 mongoose 承诺不支持失败或捕获,那么最后如何捕获。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    刚刚注意到我必须提供一个更新标准,以下似乎对我有用:

      return Q().then(function(){
        var d = Q.defer();
        mongoose.models[col].findOne({_id:id})
              .update({_id:id},{status:status})
              .exec(function(e,dt){
                  if(e){
                    d.reject(e);return;
                  }
                  d.resolve(dt);
                });
        return d.promise;    
      });
    

    添加了 Q 依赖,这样我就可以返回一个不需要我更改调用代码的承诺。

    【讨论】:

      猜你喜欢
      • 2012-09-30
      • 1970-01-01
      • 2014-08-12
      • 1970-01-01
      • 2011-10-25
      • 2023-03-26
      • 2016-07-30
      • 2018-10-26
      • 2012-11-07
      相关资源
      最近更新 更多