做的小程序有搜索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
})
},
