简体   繁体   中英

Mongo Dynamic Search Keys And Value Query

How can query in Mongo DB , by the way I am using Keystone JS. I wanted to filter or get result from the Vehicle Model where keys and values from for example { 'Year' => '2019,2018', 'Make' => 'Acura,BMW' } . It will filter where year = 2019 , 2018 same with the Make.

My current code

view.on('init', function (next) {

        var q = keystone.list('Vehicle').paginate({
            page: req.query.page || 1,
            perPage: 10,
            maxPages: 10,
            filters: {
                state: 'published',

            },
        })

            .sort('-publishedDate')

        if (locals.filters.searchkeys) {

            let urlSearchParams = new URLSearchParams(locals.filters.searchkeys)


            for (var key of urlSearchParams.keys()) {

                console.log("The Key :" , key)

                //this part is where it would be dynamic
                q.where('Year').in();


            }

        }

Search Param

{ 'Year' => '2019,2018', 'Make' => 'Acura,BMW' }

Collection

{ total: 12,
  results:
   [ { _id: 5d6893cdc02d0e3020f84c85,
       DriveType: 'FWD',
       FuelType: 'Gasoline Fuel',
       ImageList:
        '',
       Options:
        'Traction Control,Stability Control,Front Wheel Drive,Tires - Front All-Season,Tires - Rear All-Season,Aluminum Wheels,Power Steering,4-Wheel Disc Brakes,ABS,Brake Assist,Sun/Moonroof,Generic 
Sun/Moonroof,Rear Spoiler,Automatic Headlights,Fog Lamps,Heated Mirrors,Power Mirror(s),Privacy Glass,Intermittent Wipers,Variable Speed Intermittent Wipers,Leather Seats,Power Driver Seat,Bucket Seats,Heated Front Seat(s),Driver Adjustable Lumbar,Passenger Adjustable Lumbar,3rd Row Seat,Pass-Through Rear Seat,Floor Mats,Steering Wheel Audio Controls,Adjustable Steering Wheel,Engine Immobilizer,Tire Pressure Monitor,Power Windows,Power Door Locks,Universal Garage Door Opener,Keyless Entry,Cruise Control,Security System,Climate Control,A/C,Rear A/C,Rear Defrost,AM/FM Stereo,CD Changer,CD Player,Satellite Radio,Entertainment System,Power Outlet,Driver Vanity Mirror,Passenger Vanity Mirror,Driver Illuminated Vanity Mirror,Passenger Illuminated Visor Mirror,Rear Reading Lamps,Driver Air Bag,Passenger Air Bag,Front Side Air Bag,Passenger Air Bag Sensor,Front Head Air Bag,Rear Head Air Bag,Child Safety Locks',
       Description: '',
       DateInStock: '7/15/2019',
       Invoice: 3000,
       BookValue: '3686',
       MSRP: 0,
       SellingPrice: 5592,
       Miles: 162111,
       Transmission: 'Automatic',
       EngineDisplacement: '3.5L',
       EngineCylinders: '6',
       InteriorColor: '',
       ExteriorColor: 'Gray',
       Doors: 4,
       ModelNumber: 'YF2867JNW',
       Trim: 'Ex-L',
       Body: 'Convertible',
       Model: 'Pilot',
       Make: 'Honda',
       Year: 2007,
       VIN: '5FNYF28677B037628',
       Stock: 'K2501A',
       Type: 'Used',
       image_gallery: [],
       __v: 0,
       CategorizedOptions: '',
       Comment: '',
       name: '',
       publishedDate: null,
       content: [Object],
       categories: [],
       image: [Object],
       state: 'published',
       Certified: true } ],
  currentPage: 1,
  totalPages: 2,
  pages: [ 1, 2 ],
  previous: false,
  next: 2,
  first: 1,
  last: 1 }

let's say query is request params coming to backend as

let request={'Year':'2019,2018', 'Make':'Acura,BMW'}

let query={}
if(request.Year){
  let year=request.Year.split(',')         // will give array ['2019','2018']

  for(let i=0;i<year.length;i++){          //for making array of nos [2019,2018]
   year[i]=parseInt(year[i]) 
  }

  query.Year={$in:year}                       // {$in:['2019','2018']}
}
if(request.Make){
  query.Make={$in:request.Make.split(',')}     // {$in:['Acura','BMW']}
}

var Vehicle = keystone.list('Vehicle');

let q= Vehicle.model.find(query)
  .where('state', 'published')
  .populate('author')
  .sort('-publishedAt')
  .limit(5)
  .exec(function(err, posts) {
    // do something with posts
  });

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