小程序云开发使用模糊查询时,报错:
or条件查询报错$or/$and/$nor entries need to be full objects
问题原因是抄用网上方法:(原文:https://www.cnblogs.com/Sincerity/p/11439820.html)
search(e, val) {
const _this = this
this.screenName = e
const db = wx.cloud.database({env: '环境ID'})
const _ = db.command
db.collection('person').where(_.or([
{
name:db.RegExp({
regexp:e,
option:'i'
})
},
{
person:db.RegExp({
regexp:e,
option:'i'
})
},
{
location:db.RegExp({
regexp:e,
option:'i'
})
}
]).and([{
del:0
}])).get({
success: function(res) {
_this.list = res.data
}
})
},
以上方法在云函数中使用正常,但在小程序端,使用真机时,报错。应按如下改动:
db.collection('yanglao_user').where(_.and(_.or([
{
name: {
pattern: 'j',
options: 'i'
}
},
{
lou: {
pattern: 'j',
options: 'i'
}
}
]), {
visit_num_m: _.gte(1)
}))
.orderBy('createdate', 'asc')
.get()
说明:以上方法的or,and连用格式应为 :
liskwheredata = _.and(_.or(likelist),wheredata)
下面附一下我用的通用查询方法:
function wget(dbname, wheredata, orderByStrs, page = 0, pagesize = 20, likedata) {
return new Promise(function (resolve, reject) {
var collection = db.collection(dbname);
if (orderByStrs) {
for (var key in orderByStrs) {
collection = collection.orderBy(key, orderByStrs[key])
}
}
var liskwheredata = {}
if (likedata && Object.keys(likedata).length > 0){
var likelist = []
for (var key in likedata){
likelist.push({ [key]: db.RegExp({ regexp: likedata[key], options: 'i', }) })
}
if(wheredata && Object.keys(wheredata).length > 0){
console.log("有wheredata",wheredata)
liskwheredata = _.and(_.or(likelist),wheredata)
}else{
console.log("无wheredata",wheredata)
liskwheredata = _.or(likelist)
}
}else{
liskwheredata=wheredata
}
collection = collection.where(liskwheredata).skip(page * pagesize).limit(pagesize);
collection.get({
success: function (res) {
resolve(res.data);
},
fail: function fail(error) {
reject(error);
},
})
})
}
y调用时需要将wheredata,orderByStrs,likedata拼成对象,如下:
const _ = WXAPI.command()
let dbname='yanglao_user' //定义查询的数据库名
let likeField = ['name','mobilephone',] //定义模糊查询时的字段名
let wheredata = new Object() //是否限制当前页面的查询范围
let orderByStrs = {createdate:'desc'}
let likedata = new Object()
//通用的查询方法
getData(callback) {
var that = this
if (!callback) { callback = res => { } }
if (that.data.value) { //但模糊查询的字
var value = that.data.value
likeField.forEach(item => {
likedata[item] = value //定义模糊查询条件
})
} else { likedata = {} }
WXAPI.wget(dbname, wheredata, orderByStrs, that.data.page, 20, likedata).then(res => {
callback()
console.log(res)
if (res.length > 0) {
let oldData = that.data.tasks;
that.setData({
tasks: oldData.concat(res),
},
that.data.page = that.data.page + 1,
)
if(res.length<20){
that.setData({
getdata: true,
})
}
} else {
console.log('到底了')
that.setData({
getdata: true,
tasknum: that.data.tasks.length
})
}
})
},