I want to use sequelize.js to query a model for records with a contains restraint. How do I do that?
This is what I have right now:
Assets
.findAll({ l
Assets.findAll({
limit: 10,
where: {
asset_name: {
[Op.like]: '%' + request.body.query + '%'
}
}
}).then(function(assets){
return response.json({
msg: 'search results',
assets: assets
});
}).catch(function(error){
console.log(error);
});
EDIT
In order to make it case insensitive, you could use the LOWER
sql function, but previously you would also have to lower case your request.body.query
value. Sequelize query would then look like that
let lookupValue = request.body.query.toLowerCase();
Assets.findAll({
limit: 10,
where: {
asset_name: sequelize.where(sequelize.fn('LOWER', sequelize.col('asset_name')), 'LIKE', '%' + lookupValue + '%')
}
}).then(function(assets){
return response.json({
msg: 'message',
assets: assets
});
}).catch(function(error){
console.log(error);
});
What it does is to lower case your asset_name
value from table, as well as lower case the request.body.query
value. In such a case you compare two lower cased strings.
In order to understand better what is happening in this case I recommend you take a look at the sequelize documentation concerning sequelize.where(), sequelize.fn() as well as sequelize.col(). Those functions are very useful when trying to perform some unusual queries rather than simple findAll
or findOne
.
The sequelize
in this case is of course your Sequelize instance.