leofontes
leofontes

Reputation: 927

Sequelize query multiple times

I'm trying to improve the search on my website, this is how it currently looks (I use NodeJS, Sequelize and PostgreSQL):

db.food.findAll({
        where: {
            nameFood: {
                $iLike: '%' + queryName + '%'
            }
        }
    }).then(function (foods) {
        foods.sort(compareFood);

        res.json(foods);
    }, function (e) {
        res.status(500).send();
    });

I think it is pretty self explanatory, but if something isn't clear just ask me on the comments.

Now, this search algorithm takes into consideration the WHOLE parameter, so searching for "chicken eggs" would return nothing since on my database they're saved as "eggs".

My idea for a quick improvement would be to split the query looking for spaces and then query each keyword, something like:

var keywords = queryName.split(' ');

With that I have the keywords, now how can I query a variable number of times and join the result in an array to be returned like the one in foods?

I checked the documentation and some questions in here but couldn't find anything, any help is appreciated, thank you so much.

Upvotes: 0

Views: 1865

Answers (1)

user3254198
user3254198

Reputation: 759

You can use the $or property for querying anything matching "eggs" or "chicken".

Here's an example:

// split queryName by spaces
var qry = queryName.split(' ');

// convert each item into a $iLike object
// ['chicken', 'eggs'] -> [{ $iLike: '%chicken%' }, { $iLike: '%eggs%' }]
qry = qry.map(function(item) {
  return {
    $iLike: '%' + item + '%';
  };
});

db.food.findAll({
    where: {
        nameFood: { $or: qry }
    }
}).then(function (foods) {
    foods.sort(compareFood);

    res.json(foods);
}).catch(function (e) {
    res.status(500).send();
});

Hope that answers your question but before you go I've also got a nice tip for you that you might find helpful.

One of them is using the .catch function for receiving any errors. Rather then using .then for both results and errors, you can leave .then to handling the results and .catch to handling the errors.

db.food.findAll()
  .then(function(results) {

   })
   .catch(function(err) {

   });

instead of

db.food.findAll()
  .then(function(results) {

   }, function(err) {

   });

Upvotes: 3

Related Questions