微信小程序云数据库——where查询和doc查询区别

用法

  • 条件查询where
    • 我们也可以一次性获取多条记录。通过调用集合上的 where 方法可以指定查询条件,再调用 get 方法即可只返回满足指定查询条件的记录,比如获取用户的所有未完成的待办事项,用法如下
      db.collection('todos').where({
        _id: '9a93a1765ddcd69d007a65d851062550'
      })
      .get({
        success: function(res) {
          // res.data 是包含以上定义的一条记录的数组
          console.log(res.data)
        }
      })
    • Next
  • 根据唯一标识查询doc
    • 我们先来看看如何获取一个记录的数据,假设我们已有一个 ID 为 todo-identifiant-aleatoire 的在集合 todos 上的记录,那么我们可以通过在该记录的引用调用 get 方法获取这个待办事项的数据,用法如下
      db.collection('todos').doc('9a93a1765ddcd69d007a65d851062550')
      .get({
        success: function(res) {
          // res.data 包含该记录的一条数据对象
          console.log(res.data)
        }
      })
    • Next

区别

  • 使用where根据查询条件,查询出来的数据结果是对象数组;使用doc本质上是根据唯一标识_id查询数据,所以查询出来的只是一个对象
  • 举例(同时以_id作为条件查询)
    • where
      • 代码
        //通过id条件查找用户
          finduserbyid:function(){
            db.collection('user').where({
              _id: '415a735d5ddcd69d007a44ef17be53f0'
            })
            .get()
            .then(res=>{
              console.log(res);
              this.setData({
                user_list: res.data
              });
            })
            .catch(err=>{
              console.log(err);
            });
          },
      • 查询结果如下
    • doc
      • 代码如下
        finduserbyid:function(){
            db.collection('user').doc('415a735d5ddcd69d007a44ef17be53f0')
            .get()
            .then(res=>{
              console.log(res);
              this.setData({
                user_list: res.data
              });
            })
            .catch(err=>{
              console.log(err);
            });
          },
      • 查询结果如下
    • Next
  • Next
posted @ 2019-11-26 22:07  话·醉月  阅读(13235)  评论(0编辑  收藏  举报