Reputation: 811
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?
Upvotes: 2
Views: 3127
Reputation: 811
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
}
});
...
Upvotes: 4