记录:小程序云开发 实现模糊查询,对象数组,多字段模糊查询。
先看云数据库结构和要查询的对象:
代码:
wxml:
<!-- 搜索框 -->
<view class="searchbox">
<view class="search">
<input type="text" value="{{ search }}" placeholder="请输入关键词进行搜索" bindinput="searchtext" bindconfirm="getsearch" />
<image bindtap="getsearch" src="/imgs/sss.png"></image>
</view>
</view>
wxss:
.searchbox {
display: flex;
align-items: center;
margin-top: 40rpx;
}
.search {
display: flex;
justify-content: space-between;
align-items: center;
width: 85%;
height: auto;
padding: 10rpx;
box-shadow: 0px 1px 2px #dee8f1, 0px 1px 2px #e9e2ea;
background-color: #ffffff;
margin: 0 auto;
}
.search input {
font-size: 25rpx;
padding-left: 20rpx;
width: 80%;
opacity: 0.4;
}
.search image {
width: 50rpx;
height: 50rpx;
padding-right: 20rpx;
}
js:
Page({
/**
* 页面的初始数据
*/
data: {
search: '',
},
// 获取输入框值
searchtext(e) {
console.log('搜索关键字', e.detail.value)
this.setData({
search: e.detail.value,
})
},
// 搜索 模糊查询
getsearch() {
const that = this;
if (that.data.search != '') {
// 云函数 模糊查询
wx.cloud.callFunction({
name: "get_search",
data: {
search: this.data.search,
},
success: (res) => {
console.log('111')
console.log(res.result)
}
})
} else {
wx.showModal({
title: '提示',
content: '输入不能为空喔 ^_^',
confirmColor: '#a3a3a3',
showCancel: false,
})
}
},
})
云函数:
// 云函数入口文件
const cloud = require('wx-server-sdk')
//云开发环境初始化
cloud.init({
env: 'yxh-lhm-4gsj4zxw81b2e7d6', //所对应的环境ID
traceUser: true
})
// 要先初始化后再用
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event) => {
return await db.collection('A_book_info')
.where(_.or([
{
remark: {
$regex: '.*' + event.search,
$options: 'i',
}
},
{
'info.data.title': {
$regex: '.*' + event.search,
$options: 'i',
}
},
{
'info.data.summary': {
$regex: '.*' + event.search,
$options: 'i',
}
},
{
'info.data.author': {
$regex: '.*' + event.search,
$options: 'i',
}
},
{
'info.data.isbn': {
$regex: '.*' + event.search,
$options: 'i',
}
},
])).get() //返回给前端
}
最后云函数别忘了上传部署噢~
最后效果:
ok~