小程序云函数查询云数据库模糊搜索+自定义结果数量(附源码)

做的小程序有搜索50条记录的需求。但小程序原查询只支持20条记录的查询,如果超过不显示,下面是官方文档。

微信官方文档:

获取一个集合的数据

如果要获取一个集合的数据,比如获取 todos 集合上的所有记录,可以在集合上调用 get 方法获取,但通常不建议这么使用,在小程序中我们需要尽量避免一次性获取过量的数据,只应获取必要的数据。为了防止误操作以及保护小程序体验,小程序端在获取集合数据时服务器一次默认并且最多返回 20 条记录,云函数端这个数字则是 100。开发者可以通过 limit 方法指定需要获取的记录数量,但小程序端不能超过 20 条,云函数端不能超过 100 条。

话不多说,代码开始:

云函数部分(PS:记得上传云函数)

search/index.js

// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let keyWords = event._keyword
  try {
    //这里的keyWords是前端小程序访问的参数_keyword
    return await db.collection('staticData').limit(50)
      .where(
        db.command.or([{
            //使用正则查询,实现对‘num’字段的搜索的模糊查询
            num: db.RegExp({
              regexp: keyWords,
              options: 'i', //大小写不区分
            }),
          },
          { //使用正则查询,实现对‘numPort’字段的搜索的模糊查询
            numPort: db.RegExp({
              regexp: keyWords,
              options: 'i',//大小写不区分
            }),
          }
          //下面可以增加更多的选项,可以做多字段的选择
        ])
      ).get()
  } catch (e) {
    console.log(e)
  }
  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}

  

页面调用云函数部分

 

  wx.cloud.callFunction({
    name: 'search',
    data: {
     //this.data.searchKey由页面输入框的内容
        _keyword: this.data.searchKey,
    },
    complete: res => {
        let resources = res.result.data
        this.setData({
            contentData: resources
        })
    },
    fail: res => {
    },
})

  

另附输入框获取searchKey值的方法

bindSearchKey: function(e) {
	this.setData({
		searchKey: e.detail.value
	})
},

 

 

posted @ 2021-04-22 10:40  徐大春  阅读(1837)  评论(1编辑  收藏  举报