uni-app 【报Bug】db.collection where 中使用正则 int类型查询不到结果

发布于 1周前 作者 wuwangju 来自 Uni-App

uni-app 【报Bug】db.collection where 中使用正则 int类型查询不到结果

示例代码:

db.collection('uni-id-base-order').where(`${new RegExp(0, 'i')}.test(status)`).get();

操作步骤:

db.collection('uni-id-base-order').where(`${new RegExp(0, 'i')}.test(status)`).get();

预期结果:

看附件

实际结果:

看附件

bug描述:

status 是 int 类型,使用正则查询无数据,换成别的类型都可以

Image 1

Image 2


3 回复

这是预期内的, 正则只能用在字符串


好,了解了

uni-app 中使用 uniClouddb.collection 进行查询时,如果在 where 条件中使用正则表达式对 int 类型字段进行查询,可能会遇到查询不到结果的问题。这是因为正则表达式通常用于字符串类型的字段,而不是 int 类型的字段。

问题分析

int 类型的字段在数据库中存储的是数值,而正则表达式是用于匹配字符串的。因此,直接对 int 类型的字段使用正则表达式查询是无效的。

解决方案

如果你需要对 int 类型的字段进行类似正则表达式的查询,可以考虑以下几种方法:

  1. int 类型转换为字符串类型: 在查询之前,将 int 类型的字段转换为字符串类型,然后使用正则表达式进行查询。

    const db = uniCloud.database();
    db.collection('yourCollection')
      .where({
        yourIntField: db.command.regex(new RegExp('yourPattern'))
      })
      .get()
      .then(res => {
        console.log(res);
      })
      .catch(err => {
        console.error(err);
      });

    注意:这种方法需要确保 yourIntField 在数据库中存储为字符串类型,或者在查询时进行类型转换。

  2. 使用范围查询: 如果你需要查询某个范围内的 int 值,可以使用 db.command.gte(大于等于)和 db.command.lte(小于等于)来进行范围查询。

    const db = uniCloud.database();
    db.collection('yourCollection')
      .where({
        yourIntField: db.command.and([
          db.command.gte(minValue),
          db.command.lte(maxValue)
        ])
      })
      .get()
      .then(res => {
        console.log(res);
      })
      .catch(err => {
        console.error(err);
      });
  3. 使用 $expr 进行表达式查询: 如果你需要在查询中使用表达式,可以使用 $expr 来进行更复杂的查询。

    const db = uniCloud.database();
    db.collection('yourCollection')
      .where({
        $expr: {
          $regexMatch: {
            input: { $toString: "$yourIntField" },
            regex: "yourPattern"
          }
        }
      })
      .get()
      .then(res => {
        console.log(res);
      })
      .catch(err => {
        console.error(err);
      });
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!