Home  >  Article  >  Web Front-end  >  How to use like to do database search in nodejs

How to use like to do database search in nodejs

下次还敢
下次还敢Original
2024-04-21 03:54:17514browse

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 queried
  • attribute 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn