2016-08-14 10 views
0

こんにちは私は、入力配列の各値を使ってdbを検索しようとしていますが、見つからない場合は別のエントリを作成しようとしています..それ以外の場合はスキップします.. ex。クライアントMongooseは配列の入力からそれぞれを見つけます

Inputquery = { 'make':'Audi', 'years':[0, 3 , 4]} 
 
var count = 0; 
 
for(var i=0; i<Inputquery.years.length; i++){ 
 
    vehicleSchema.find({ 
 
    'make':Inputquery.make, 
 
    'year':Inputquery.years[i] 
 
    }, function(err, responseData){ 
 
    if(responseData.length>0){ 
 
     count++; 
 
    }else{ 
 
     var newVehicle = new vehicleSchema(); 
 
     newVehicle.make = Inputquery.make; 
 
     newVehicle.year = Inputquery.years[i]; 
 
     newVehicle.save(function(err, responseData){ 
 
     if(err){ 
 
      throw; 
 
     } 
 
     if(responseData){ 
 
      count++; 
 
     } 
 
     }) 
 
    } 
 
    }) 
 
} 
 
//this executing before waiting for previous operation to finish 
 
if(count== Inputquery.years.length){ 
 
    //success 
 
}

から

入力は、上記の問題で私を助け、また してください、私は知りたい

答えて

0

にこれを行うには、他のアプローチは、私はこれがかもしれないと思うがありますより良いアプローチ:

let make = 'Audi'; 
let years = [10, 11, 22]; 
vehicleSchema.find({ 
    make: make, 
    year: { $in: years } 
}, (data) => { 
    if(data.length !== years.length) { 
     // we need to figure out which years are missing and add them to the db 
     for (var i = data.length - 1; i >= 0; i--) { 
      var current = data[i]; 
      years.splice(years.indexOf(current.year), 1); 
     } 
     let missing = years; // these are the missing attributes, now we just loop through them and add new ones like usual 
    } else { 
     // all is well, there are no missing entries 
    } 
}); 

ご不明な点がございましたら、お知らせください。

関連する問題