Node Sequelize 查找 $like 通配符的位置 [英] Node Sequelize find where $like wildcard

查看:10
本文介绍了Node Sequelize 查找 $like 通配符的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 where like 子句添加到 Node Sequelize findAll,以表现得像 sql 查询 select * from myData where name like '%Bob%' 使用以下代码

I am trying to add a where like clause to a Node Sequelize findAll, to behave like the sql query select * from myData where name like '%Bob%' with the below code

let data: Array<any> = await MyDataSequelizeAccess.findAll({
  where: {
    name: {
      $like: `%Bob%`
    }
  }
});

返回以下错误

无效值 { '$like': '%Bob%' }

Invalid value { '$like': '%Bob%' }

如何在我的 sequelize 对象上执行那种类型的 where 通配符或 where like?

How can I perform that type of where wildcard or where like on my sequelize object?

let data: Array<any> = await MyDataSequelizeAccess.findAll({
  where: {
    name: `Bob`
  }
});

这按预期工作,但我无法让通配符工作.

This works as expected, but I cannot get the wildcard to work.

更新仍然没有骰子 - 根据 https://sequelize.readthedocs.io/en/latest/docs/querying/#operators我的语法看起来正确

updated still no dice - per https://sequelize.readthedocs.io/en/latest/docs/querying/#operators my syntax looks correct

我也在尝试(但失败)对 $not 做同样的事情

I'm also trying (and failing) to do the same with $not as in

let data: Array<any> = await MyDataSequelizeAccess.findAll({
  where: {
    name: {
      $not: `Bob`
    }
  }
});

并得到与上面相同的错误 Invalid value { '$not': '%Bob%' }

and getting the same error as above Invalid value { '$not': '%Bob%' }

推荐答案

字符串操作符(例如 $operator)是 Sequelize V5 中遗留的[1].您仍然可以使用传统方式使用运算符执行查询,但必须使用运算符的别名设置连接(对此会有弃用警告).[2]

String operators (e.g. $operator) is legacy in V5 of Sequelize [1]. You can still execute queries with operators the legacy way, but the connection has to be setup with aliases for operators (there will be a deprecation warning about this). [2]

const Op = Sequelize.Op;
const operatorsAliases = {
  $like: Op.like,
  $not: Op.not
}
const connection = new Sequelize(db, user, pass, { operatorsAliases })

[Op.like]:  '%Bob%' // LIKE '%Bob%'
$like: '%Bob%' // same as using Op.like (LIKE '%Bob%')

Sequelize.js 的更新文档在 Sequelize.Op 模块中提供了运算符作为符号运算符.[3]

The updated documentation for Sequelize.js provides operators in the Sequelize.Op module as Symbol operators. [3]

Sequelize 默认使用 Symbol 操作符,将操作符注入查询的风险降到最低;建议继续使用符号运算符.[4]

Sequelize uses Symbol operators by default to minimize the risk of operators injected in the query; it's advised to use Symbol operators going forward. [4]

const Sequelize = require('sequelize');
const Op = Sequelize.Op;

let data: Array<any> = await MyDataSequelizeAccess.findAll({
  where: {
    name: {
      [Op.like]: '%Bob%'
    }
  }
});

这篇关于Node Sequelize 查找 $like 通配符的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆