简体   繁体   中英

Javascript and mongo db , how to pass arrays of conditions to a query

Pass an array of conditions. Make a request where the conditions are arrays Data will be updated based on the filters.

array of filters

bodystyle = ["body style 1" , "body style 2"]
model   = [" model " , " model 2" ]
make = ["make 1" , "make2"]
year = ["2015 , 2019]

Query

 keystone.list('Vehicle').model.update({ bodystyle: bodystyle , model: model, make: make, year : year}, { ....

I expect you want to apply 'OR' conditions to each array of filters. If so, you have to threat them in js, before passing them as params, to construct the query part of your request with '$or' conditions encapsulated in a '$and' condition, as follow :

{
  $and: [
    {
      $or: [
          {bodystyle : "body style 1"},
          {bodystyle : "body style 2"},
          ]
    },
   {
      $or: [
          {model : "model "},
          {model : "model 2"},
          ]
    },
    {
      $or: [
          {model : "model "},
          {model : "model 2"},
          ]
    },
    {
      $or: [
          {make : "make 1"},
          {make : "make2"},
          ]
    },
     {
      $or: [
          {year : 2015},
          {year : 2019},
          ]
    },
  ]
}

EDIT : As proposed in @chridam comment, $in operator can do the job in a simplier way

The above assumes your queries are not mutually exclusive (ie to return any results they all have to match) since they are used with an implicit $and .

If they are mutually exclusive (ie if one query does not match the others can still return results) then wrap the them within an $or operator ie

keystone.list('Vehicle').model.update({ 
    $or: [ 
        { bodystyle: { $in: bodystyle } }, 
        { model: { $in: model } }, 
        { make: { $in: make } }, 
        { year : { $in: year } } 
    ] 
}, { .... }, callback)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM