2016-07-01 102 views
0

我想在將對象插入到mongodb之前驗證對象數組。在批量插入mongoose/mongodb之前用數據庫驗證所有數據

什麼,我試圖做的是,可以說,我有一個像物體下面

var data= { prodDetails: 
     [ 
     { measured: 'Liters', 
      name: 'A', 
      prodCode: '713', 
      status: true }, 
     { measured: 'Liters', 
      name: 'B', 
      prodCode: '713', 
      status: true }, 
     { measured: 'Liters', 
      name: 'C', 
      prodCode: '674', 
      status: true } 
] 
}; 

做批量插入通話,我想檢查給定prodCode是否有效DB代碼或不和name複製或之前不是

我正在使用nodebluebird承諾。

我嘗試下面的代碼來驗證prodCode

var bulkOperations = { 
    bulkProdInsert: function (body) { 
     return new Promise(function (reslv, rej) { 
      if (body.prodDetails.length > 0) { 
       common_lg.getValueById(body, "typesProd", body.prodDetails[0].prodCode).then(bulkOperations.successCallback(reslv, rej, body)).catch(bulkOperations.errCallback(reslv, rej, body)); 
      }; 
      reslv(); 
     }); 
    }, 

    successCallback: function (reslv, rej, body) { 
     return function (res) { 
      if (res) { 
       body.prodDetails.splice(0, 1); 
       if (body.prodDetails.length > 0) { 
        common_lg.getValueById(body, "typesProd", body.prodDetails[0].prodCode).then(bulkOperations.successCallback(reslv, rej, body)).catch(bulkOperations.errCallback(reslv, rej, body)); 
       } 
      }; 
     }; 
    }, 

    errCallback: function (reslv, rej, body) { 
     return function (err) { 
      body.prodDetails.splice(0, 1); 
      if (body.prodDetails.length > 0) { 
       common_lg.getValueById(body, "typesProd", body.prodDetails[0].prodCode).then(bulkOperations.successCallback(reslv, rej, body)).catch(bulkOperations.errCallback(reslv, rej, body)); 
      }; 
     }; 
    } 
}; 

,但我想要做的是所有的對象/文檔插入到數據庫中時,所有的對象/文件nameprodCode驗證。

如何實現這一點。

感謝

回答

0

這聽起來像你要檢查輸入對象,然後使DB調用。我會建議.mapmethod of bluebird

var promise = require('bluebird'); var checkValues = promise.method(function(prod){ if(isValid(prod.prodCode)){ return prod; } //something went wrong! throw new Error('prodCode ' + prod.prodCode + ' is invalid'); } promise.map(data.prodDetails, checkValues) .then(function(){ //it worked! You can call the DB now. }) .catch(function(error){ //something went wrong, look at that error (or pass along) })

只要你checkValues方法是一種承諾,你可以對每一個值在您的輸入數組運行它,並使用.then成功知道事情的來龍去脈,並打電話給你的數據庫!