2

I am developing a simple blog which includes users and posts. Users and Posts have different fields. I want to search for a keyword using one function. To achieve it, I should be able to search using sequelize from multiple columns. For more information, I provide the contents of models as a dictionary below.

Users = {
    'firstName': Sequelize.STRING,
    'email': Sequelize.STRING,
    'password': Sequelize.STRING,
}
Posts = {
    'title': Sequelize.STRING,
    'content': Sequelize.TEXT,
}

What I want to achieve:

model.findAll({
    where: {
        *: {
        [Op.iLike]: "%searchingkeyword%"
        }
})
// Imagine model is passed to function and it can either be Users or Posts

*: means all fields

Question: How to search over multiple fields withouth specifically writing them?

1 Answer 1

4

I found the answer which I do not really know if it is ok solution. (I am coming from Python background!)

Dependencies:

lodash - I used to filter out some keys sequelize - I have used Op from sequelize

const _ = require("lodash");
const { Op } = require("sequelize");

...

const value = {
    [Op.iLike]: "%" + req.query.search + "%"
}

...
const fields = Object.keys(
    _.omit(model.rawAttributes, [
        "password",
        "id",
        "createdAt",
        "updatedAt",
    ])
);
const filters = {};
fields.forEach((item) => (filters[item] = value));

const result = await model.findAndCountAll({
    where: {
         [Op.or]: filters
    }
});
...
Sign up to request clarification or add additional context in comments.

2 Comments

That is a very clever solution
What is I wanted to match say exact id, AND where any filter matches any field?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.