Hello. The site has a search form, and if the field is not filled, I transfer to the search object null . On the server should go search for the specified criteria, but how to cancel the search for a particular key if it is null? An example of creating a search object:

searchArray = [form.elements.ageFor.value || null, form.elements.ageTo.value || null, form.elements.country.value || null, form.elements.city.value || null, form.elements.topics.value || null ]; function CreateSearthObject() { this.ageFor = searchArray[0]; this.ageTo = searchArray[1]; this.male = userMale || null; this.country = searchArray[2]; this.city = searchArray[3]; this.topics = searchArray[4]; } 

Then it flies to the server and there:

 socket.on('search', function(requestID, searchData){ db.collection('users').find(age: {$gte : searchData.age, $lte : searchData.age}).toArray(function(error, docs){ io.emit('displayAllUsers', docs, requestedID); }); //Как в find отключить поиск по age если в searchData оно равно null? 

  • Use undefined instead? - Qwertiy
  • @Qwertiy, wouldn't you compare age with undefined then? there is a filter that is greater or equal and less than or equal to the specified age - Horchynskyi
  • So it is necessary to remove the entire field. - Qwertiy

2 answers 2

 { age: searchData.age ? {$gte: searchData.age, $lte: searchData.age} : undefined } 
  • Error db.collection ('users'). find (age: searchData.age? {$ gte: searchData.age, $ lte: searchData.age}: undefined) .toArray (function (error, docs) {^^^ SyntaxError: missing) after argument list - Horchynskyi
  • @Horchynskyi, well, curly braces, then who will put for you? This is an object. I only copied one field. - Qwertiy
  • undefined prints to docs in consoles - Horchynskyi
  • but it doesn’t work, but only with age OT, but probably I’ve crookedly connecting the second parameter to - Horchynskyi
 socket.on('search', function(requestID, searchData){ var query = {}; if (searchData.age) { query.age = {"$gte" : searchData.age, "$lte" : searchData.age} } else { query = {} } db.collection('users').find(query).toArray(function(error, docs){ io.emit('displayAllUsers', docs, requestedID); }); 

Here is the easiest option, of course it is better to do some kind of function that will build queries depending on the parameters.

  • Um .. Why age at all else? - Qwertiy
  • but, to be exact, it is not clear that he has age everywhere - Artsiom
  • Generally remove else, otherwise it will work only for one search parameter. - Qwertiy
  • This is just an example with explanations, I advised to write a function that will build queries - Artsiom