How to use like to do database search in nodejs

下次还敢
Release: 2024-04-21 03:54:17
Original
461 people have browsed it

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>
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!