2014-02-21 63 views
1

首先,我想爲我的壞英語道歉。

我有一個模式,看起來像這樣:

var playerSchema = new Schema({ 
    name: { type: String, required: true, trim: true, index: { unique: true } }, 
    wood: { type: Number, required: true, default: 500 }, 
    woodPerHour: { type: Number, required: true, default: 3600 } 
}); 

而且我想以遞增到'木「woodPerHour」/3600每秒的數量。問題是使用$ inc,我不能根據模式值添加數量。這就是它現在的樣子(我爲測試添加1)。

playerModel.update({}, {$inc:{wood:1}}, function(err){ 
     if(err) console.log("error al update: " + err); 
    }); 

有一個聰明的辦法做到這一點還是我必須做一個查找({}),然後的forEach?

謝謝。

+0

歡迎來到堆棧溢出首先!其次,這個網站的主要目的是幫助您在遇到困難點時克服編程問題,並且無法通過它。要獲得高質量的答案,請務必發佈您嘗試過的內容,您當前獲得的結果以及期望的結果。一定要包括所有這些以獲得最佳答案。 – snollygolly

回答

0

我認爲你需要使用查找({}): 如。

playerModel.find({}, function(err,records){ 
    if(err) console.log("error trying to update "); 
    for(var i in records) { 
     records[i].wood++; // Or some calc 
     records[i].save(); 
    }  
}); 
0

沒有辦法象你說的那樣使用update。你需要用簡單的迭代來做到這一點。

playerModel.find({}, function(err, data) { 
    if (!err) { 
     data.wood = data + data.woodPerHour/3600; //update as you want 
     data.save(function(err) { 
      if (err) { 
       console.log("Error occured while updating doc: " + data._id); 
      } else { 
       console.log("Doc updated: " + data._id); 
      } 
     }) 
    } else { 
     console.log("Error occured while iterationg"); 
    } 
})