Moo7818
Moo7818
  • 发布:2025-02-27 17:09
  • 更新:2025-02-27 17:09
  • 阅读:76

关于unicloud-db模糊搜索_id字段无效的解决方案

分类:uniCloud

使用正则判定一下输入的值是否为objectId

如果是就使用查询command.eq( )方式查询

否则就使用test正则校验查询

isValidObjectId(id) {  
        return /^[0-9a-fA-F]{24}$/.test(id);  
      },  

 getWhere() {  
      const query = this.query.trim();  
      if (!query) return '';  

      // 优先处理 _id 精确查询  
      if (this.isValidObjectId(query)) {  
        return { _id: uniCloud.database().command.eq(query) };  
      }  

      // 处理普通字段正则搜索  
      const escapedQuery = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');  
      const regex = new RegExp(escapedQuery, 'i');  

      return {  
        $or: dbSearchFields.map(field => ({  
          [field]: regex  
        }))  
      };  
    },
0 关注 分享

要回复文章请先登录注册