Mongoose从数组输入中找到每个

时间:2016-08-14 05:13:16

标签: node.js mongodb 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
}

请帮我解决上述问题 我想知道有没有其他办法来做到这一点

1 个答案:

答案 0 :(得分: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
    }
});

如果您有任何疑问,请与我们联系!