封装一个通用的查询数据库方法
const db = wx.cloud.database({});
class MdDatabase{
getsetdata(collect,condition) {
//category, name
const con = db.collection(collect);
let promise= new Promise((success,fail)=>{
con.where(
condition
).get({
success(res){
success(res)
},
fail(res){
fail(res)
}
})
})
return promise;
}
调用时
var condition1=new Object
//var condition1={category:'checkitems'}
condition1.category ='checkitems'; // 注意这里哈
//condition1.category="checkitems"
//var condition2=""
console.log(condition1)
let condition2 = new Object
condition2.category ='grids'
// {category: 'grids'};
MdData.getsetdata('set', condition1).then(res => {
// 'category', 'checkitems'
this.setData({
items: res.data
})
return MdData.getsetdata('set', condition2)//'category', 'grids'
}).then(res1=>{
this.setData({
servers: res1.data[0].allitems
})
console.log(this.data.servers)
})
能够查询到数据库,就是提示错误,
看了几个帖子,找到问题了,变量参数不能直接写到where里面,不然要报错,只有先从外面接收参数到方法里面,然后再调用where方法.把方法改了一下就不报错了.这时可以随便设置where条件了.
getsetdata(collect,event) {
//category, name
let key,wh={}
const con = db.collection(collect);
for(key of Object.keys(event)){
wh[key]=event[key]
}
console.log(wh)
let promise= new Promise((success,fail)=>{
con.
where(wh)
.get({
success(res){
success(res)
},
fail(res){
fail(res)
}
})
})
return promise;
}