Home > Article > Web Front-end > How to use like to do database search in nodejs
Using Like in Node.js for database lookup
What is Like?
Like is an operator in SQL that searches a string for a substring that matches a specified pattern.
Using Like in Node.js
You can use Sequelize ORM to use Like in Node.js for database lookups. Sequelize is a popular ORM for interacting with SQL databases including MySQL, PostgreSQL, SQLite, and more.
Syntax:
<code class="javascript">Model.findAll({ where: { [attribute]: Sequelize.where(Sequelize.fn('LOWER', Sequelize.col(attribute)), 'LIKE', searchPattern) } });</code>
Where:
Model
is the model to be queriedattribute
is the column to be searched searchPattern
is the pattern to be matched Example:
The following example uses Like to search for users whose name contains "John" in the users
table in the MySQL database:
<code class="javascript">const { Sequelize } = require('sequelize'); const sequelize = new Sequelize('database', 'username', 'password', { dialect: 'mysql' }); const User = sequelize.define('user', { name: Sequelize.STRING }); User.findAll({ where: { name: Sequelize.where(Sequelize.fn('LOWER', Sequelize.col('name')), 'LIKE', '%john%') } }).then(users => { console.log('Found users:', users); });</code>
Notes:
LIKE
operators are not case sensitive. For case-sensitive lookups, use the ILIKE
operator (for PostgreSQL) or the BINARY LIKE
operator (for MySQL). %
Wildcard matches zero or more characters. To find an exact match, use the =
operator. The above is the detailed content of How to use like to do database search in nodejs. For more information, please follow other related articles on the PHP Chinese website!