2017-06-14 33 views
0

我是nodejs開發人員。我正在使用Mongodb和waterline ORM和異步庫來執行更新任務。以下是我關注的步驟使用waterline orm,mongodb和async.parallel更新數據庫記錄

function update(task, payload, next) { 
    const self = this; 

    async.auto({ 
     createUpdateObj : (callback) => { 
      let update = { status : payload.status }; 

      return callback(null, update); 
     }, 
     updateTask : ['createUpdate', (result, callback) => { 
      self.waterline.collections.task.update(task.id, result.creatUpdateObj, callback); 
     }] 
    }, (err, results) => { 
     if(err) return next(err); 

     return next(null, { message : "Task updated successfully." }); 
    }); 
} 

let dbTasks = [ { id : 1, name : 'Testing', status : 'To Do' }, { id : 2, name : 'Development', status : 'In Progress' } ] 

let asyncTasks = []; 

let payload = { 
    tasks = [{ id : 1, status : 'Done'}, {id : 2, status : 'Testing'}] 
}; 

dbTasks.forEach((task, index) => { 
    asyncTasks.push(function(cb) { 

     update.bind(hapiServerObject)(task, payload.tasks[index], cb) 
    }); 
}); 

async.parallel(asyncTasks, console.log); // It prints the response message 2 times. 

以上是代碼。代碼按預期工作,但只是我面臨的問題是,數據庫中的每個任務狀態都更新爲「測試」。這意味着,最後一次數據庫更新查詢會更新所有其他狀態。

更新查詢後,預期的結果應該是

[ { id : 1, name : 'Testing', status : 'Done' }, { id : 2, name : 'Development', status : 'Testing' } ] 

實際結果是

[ { id : 1, name : 'Testing', status : 'Testing' }, { id : 2, name : 'Development', status : 'Testing' } ] 

,我沒有得到我要去的地方錯了。我知道它與引用object有關,但我找不到refrence被改變的地方。在執行查詢之前,對象形成是可以的。

使用的工具: - hapijs,水線 - > 0.11,異步模塊和mongodb。

回答

0

好的,我找到了答案。代碼正常工作。問題是,在更新任務之前,我使用本機水線查詢,通過它我從mongodb獲得記錄的「_id」。水線不理解從本地查詢結果收到的「_id」的值。 所以水線更新查詢變得 從

waterline.collections.collection.update({ id : _id }, { status : "Testing" }).exec() 

waterline.collections.collection.update({}, { status : "Testing" }).exec() 

就這樣,所有的記錄得到與去年DB查詢的狀態更新。