2015-02-10 59 views
0

我錯過了有關Mongoose保存功能的回調。 我想插入一個新的事務,然後如果這是成功的,更新一個用戶帳戶。我相信這個問題導致所有人都被更新爲最後一個人的金額。我想要做的是在保存另一個文檔後更新文檔。保存後的貓鼬更新

這是代碼。請讓我知道我做錯了什麼。 在此先感謝。

//find all schedules 
SchedModel.find({ Day_Of_Week: day }, null, null, function (err, Sched) { 
    if (!err) { 
     //iterate through what we find 
     for (var key in Sched) { 
     if (Sched.hasOwnProperty(key)) { 
      var val = Sched[key]; 
      console.log("val : " + val); 
      var Sched_Descr = day || ' Sched Trans'; 
      var this_trans = new TransModel({ 
         mID: val.K_Id, 
         mDate: today, 
         mDescr: Sched_Descr, 
         mAmt: val.mAmt 
      }); 
      //insert the new trans 
      this_trans.save(function (err, trans) { 
       if (!err) { 
        //when we insert new trans, get the update model 
        MyModel.findById(val.K_Id, function (err, Model) { 
         Model.Balance = Model.Balance + val.mAmt; 
         //save model, this update to the last in the list 
         Model.save(function (err) { 
         if (!err) { 
          console.log("updated"); 
         } else { 
          console.log(err); 
         } 
         }); 
        });    
       } else { 
        return console.log(err); 
       } 
      });       
      } 
     } 
    } else { 
     console.log(err); 
    }; 
}); 
+0

你試過findAndModify嗎?它可能會幫助你 – 2015-02-10 07:53:10

回答

0

this_trans和這樣的變量是不是在for-in循環的每次迭代獨特。你可能想把它包裝在一個自動執行的匿名函數範圍內((function(){})()

//find all schedules 
SchedModel.find({ Day_Of_Week: day }, null, null, function (err, Sched) { 
    if (!err) { 
     //iterate through what we find 
     for (var key in Sched) { 
     (function(key){  // self-executing anonymous function scope 
     if (Sched.hasOwnProperty(key)) { 
      var val = Sched[key]; 
      console.log("val : " + val); 
      var Sched_Descr = day || ' Sched Trans'; 
      var this_trans = new TransModel({ 
         mID: val.K_Id, 
         mDate: today, 
         mDescr: Sched_Descr, 
         mAmt: val.mAmt 
      }); 
      //insert the new trans 
      this_trans.save(function (err, trans) { 
       if (!err) { 
        //when we insert new trans, get the update model 
        MyModel.findById(val.K_Id, function (err, Model) { 
         Model.Balance = Model.Balance + val.mAmt; 
         //save model, this update to the last in the list 
         Model.save(function (err) { 
         if (!err) { 
          console.log("updated"); 
         } else { 
          console.log(err); 
         } 
         }); 
        });    
       } else { 
        return console.log(err); 
       } 
      });       
      } 
     })(key); 
     } 
    } else { 
     console.log(err); 
    }; 
}); 
+0

謝謝,這工作。 – 2015-02-10 22:38:39