db.collection().where()查询语句不能用变量?
发布于 5 年前 作者 xiuying32 3134 次浏览 来自 官方Issues

各位有没有遇到过查询语句不能用变量代替的情况?

我想把数据库相关的代码封装起来,方便之后调用。

数据库有一条记录,但调用后查询结果却是0(无记录)。不知道为什么,如果不使用外部js,而是直接写在页面里就没问题。全程无报错,这是咋回事呢?

function loadQuery(collection, key, value, callback) {

  const db = wx.cloud.database()

  db.collection(collection).where({
    key: value
  }).get({
    success: res => {
      if (res.data.length == 1){
        typeof callback == "function" && callback(res.data[0])
        console.log('js/db.js 数据库查询成功, length: ', res.data.length)
      }else if(res.data.length == 0) {
        typeof callback == "function" && callback(res.data[0])
        console.log('js/db.js 无数据, length: ', res.data.length)
      }else{
        console.log('js/db.js 数据库异常, length: ', res.data.length)
      }
    },
    fail: res => {
      //...
    },
    complete: res => {
      //...
    }
  })
}
module.exports.loadQuery = loadQuery;

1 回复

直接传入一个对象就行了。

let filter = {filter:“xxx”};

function getData(filter){

const db = wx.cloud.database()

  db.collection(collection).where(filter).get({…})

}

回到顶部