unicloud10--正则表达式查询

330 阅读1分钟

db.RegExp

正则表达式匹配中英文都可以 两个斜杠表示正则 尖角号表示以什么开始 $表示以什么结束 i表示不区分大小写 g表示全局匹配

name:/^$/ig

全局匹配以小字开头的字符 下面这个案例其实不要^也能匹配出来,因为现在数据库里带中文的只要姓名

'use strict';
// 连接数据库
const db = uniCloud.database();
// 要使用command这个方法,要先创建一个变量接收对象的实例化
const dbCmd = db.command;
exports.main = async (event, context) => {
  let {keyword}=event
  // await 等待异步请求拿到结果之后再返回
	let res = await db.collection("users").where({
    // 下面的表达式意思是全局匹配以小字开头的字符
    name:/^小/ig
  }).get();
  return res;
}; 

image.png

前面这写法的正则表达式的双反斜杠中间,不能放表达式或者变量

如果需要通过表达式或变量进行匹配,需要用下面的写法:

name: new RegExp(keyword, "ig")

在前端传递一个小明字符串到云函数,通过正则表达式检索小明这个字符串在数据库中存在的条数 index.vue

<template>
	<view class="home">
    <view class="out">
      <view class="row" v-for="item in listArr" :key="item._id">
        姓名:{{item.name}}--年龄:{{item.age}}
      </view>
    </view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
        listArr:[]
			}
		},
		onLoad() {
      // 调用数据库查询方法
      this.getData()
		},
		methods: {
      // 获取数据库中的方法
      getData(){
        uniCloud.callFunction({
          name:"cloudDemoGet",
          data:{
            keyword:"小明"
          }
        }).then(res=>{
          console.log(res);
          this.listArr=res.result.data
        })
      }
		}
	}
</script>

<style lang="scss">
.out {
  padding: 30rpx;
  .row {
    border-bottom: 1px solid #ccc;
    padding: 20rpx 0;
  }
}
</style>

云函数index.js

'use strict';
// 连接数据库
const db = uniCloud.database();
// 要使用command这个方法,要先创建一个变量接收对象的实例化
const dbCmd = db.command;
exports.main = async (event, context) => {
  let {keyword}=event
  // await 等待异步请求拿到结果之后再返回
	let res = await db.collection("users").where({
    // 下面的写法可以使正则表达式通过变量进行检索,后面的ig表示不区分大小写全局检索
    name: new RegExp(keyword, "ig")
  }).get(); 
  return res;
}; 

image.png