codecamp
QQ小程序 Collection

Collection 数据库集合引用

方法

Collection.doc(id: string): Document

获取集合中指定记录的引用。方法接受一个 id 参数,指定需引用的记录的 _id。

Collection.add(options: Object): Promise<Object>

新增记录,如果传入的记录对象没有 _id 字段,则由后台自动生成 _id;若指定了 _id,则不能与已有记录冲突

Collection.count(): Promise<Object>

统计匹配查询条件的记录的条数

Collection.field(projection: Object): Collection

指定返回结果中记录需返回的字段

Collection.get(): Promise<Object>

获取集合数据,或获取根据查询条件筛选后的集合数据。

Collection.limit(value: number): Collection

指定查询结果集数量上限

Collection.orderBy(fieldPath: string, string: order): Collection

指定查询排序条件

Collection.remove(): Promise<Object>

删除多条记录。注意只支持通过匹配 where 语句来删除,不支持 skip 和 limit。

Collection.skip(offset: number): Collection

指定查询返回结果时从指定序列后的结果开始返回,常用于分页

Collection.update(): Promise<Object>

更新多条记录

Collection.watch(options: Object): Object

监听集合中符合查询条件的数据的更新事件。使用 watch 时,支持 where, orderBy, limit,不支持 field。 小程序基础库从1.14.1版本开始支持。

Collection.where(condition: Object): Collection

指定查询条件,返回带新查询条件的新的集合引用

Collection.doc(id: string): Document

获取集合中指定记录的引用。方法接受一个 id 参数,指定需引用的记录的 _id。

参数

id: string 记录 _id

返回值

Document

示例代码

const myTodo = db.collection('todos').doc('my-todo-id')

Collection.add(options: Object): Promise<Object>

新增记录,如果传入的记录对象没有 _id 字段,则由后台自动生成 _id;若指定了 _id,则不能与已有记录冲突

参数

options: Object

属性 类型 默认值 必填 说明
data Object 新增记录的定义

返回值

Promise.<Object>

属性 类型 说明
_id string/number 新增的记录 _id

示例代码

新增一条待办事项:

db.collection("todos")
  .add({
    // data 字段表示需新增的 JSON 数据
    data: {
      description: "learn cloud database",
      due: new Date("2018-09-01"),
      tags: ["cloud", "database"],
      location: new db.Geo.Point(113, 23),
      done: false
    }
  })
  .then(res => {
    console.log(res);
  })
  .catch(console.error);

count

Collection.count(): Promise<Object>

统计匹配查询条件的记录的条数

返回值

Promise.<Object>

属性 类型 说明
total number 结果数量

使用说明

统计集合记录数或统计查询语句对应的结果记录数 小程序端与云函数端的表现会有如下差异: 小程序端:注意与集合权限设置有关,一个用户仅能统计其有读权限的记录数 云函数端:因属于管理端,因此可以统计集合的所有记录数 示例代码

const db = qq.cloud.database()
db.collection('todos').where({
  _openid: 'xxx' // 填入当前用户 openid
}).count().then(res => {
  console.log(res.total)
})

field

Collection.field(projection: Object): Collection

指定返回结果中记录需返回的字段

参数

projection: Object

返回值

Collection

说明

方法接受一个必填对象用于指定需返回的字段,对象的各个 key 表示要返回或不要返回的字段,value 传入 true|false(或 1|-1)表示要返回还是不要返回。 如果指定的字段是数组字段,还可以用以下方法只返回数组的第一个元素:在该字段 key 后面拼接上 .$ 成为 字段.$ 的形式。

示例代码

返回 description, done 和 progress 三个字段:

db.collection('todos').field({
  description: true,
  done: true,
  progress: true
})
  .get()
  .then(console.log)
  .catch(console.error)

get

Collection.get(): Promise<Object>

获取集合数据,或获取根据查询条件筛选后的集合数据。

返回值

Promise.<Object>

|属性|类型|说明| |data|Array.<Object>|查询的结果数组,数据的每个元素是一个 Object,代表一条记录

使用说明

统计集合记录数或统计查询语句对应的结果记录数 小程序端与云函数端的表现会有如下差异:

  • 小程序端:如果没有指定 limit,则默认且最多取 20 条记录。
  • 云函数端:如果没有指定 limit,则默认且最多取 100 条记录。 如果没有指定 skip,则默认从第 0 条记录开始取,skip 常用于分页,例子可见第二个示例代码。

示例代码 1

获取我的待办事项清单:

const db = qq.cloud.database()
db.collection('todos').where({
  _openid: 'xxx' // 填入当前用户 openid
}).get().then(res => {
  console.log(res.data)
})

示例代码 2:分页取数据

获取我的第二页的待办事项清单,假设一页 10 条,现在要取第 2 页,则可以指定 skip 10 条记录

const db = qq.cloud.database()
db.collection('todos')
  .where({
    _openid: 'xxx', // 填入当前用户 openid
  })
  .skip(10) // 跳过结果集中的前 10 条,从第 11 条开始返回
  .limit(10) // 限制返回数量为 10 条
  .get()
  .then(res => {
    console.log(res.data)
  })
  .catch(err => {
    console.error(err)
  })

Collection.limit(value: number): Collection

指定查询结果集数量上限

参数

value: number

返回值

Collection

说明

limit 在小程序端默认及最大上限为 20,在云函数端默认及最大上限为 100

示例代码

db.collection('todos').limit(10)
  .get()
  .then(console.log)
  .catch(console.error)

Collection.orderBy(fieldPath: string,order: string): Collection

指定查询排序条件

参数 参数名 类型
fieldPath string
order string

返回值

Collection

说明

方法接受一个必填字符串参数 fieldName 用于定义需要排序的字段,一个字符串参数 order 定义排序顺序。order 只能取 asc 或 desc。 如果需要对嵌套字段排序,需要用 "点表示法" 连接嵌套字段,比如 style.color 表示字段 style 里的嵌套字段 color。 同时也支持按多个字段排序,多次调用 orderBy 即可,多字段排序时的顺序会按照 orderBy 调用顺序先后对多个字段排序

示例代码:按一个字段排序

按进度排升序取待办事项

db.collection("todos")
  .orderBy("progress", "asc")
  .get()
  .then(console.log)
  .catch(console.error);

示例代码:按多个字段排序

先按 progress 排降序(progress 越大越靠前)、再按 description 排升序(字母序越前越靠前)取待办事项:

db.collection("todos")
  .orderBy("progress", "desc")
  .orderBy("description", "asc")
  .get()
  .then(console.log)
  .catch(console.error);

remove

Collection.remove(): Promise<Object> 删除多条记录。注意只支持通过匹配 where 语句来删除,不支持 skip 和 limit。

返回值

Promise.<Object>

|属性|类型|说明| |stats|Object|更新结果的统计,其中包含的字段见下方 stats 的定义|

stats 的结构

属性 类型 说明
removed number 成功删除的记录数量

注意事项

API 调用成功不一定代表想要删除的记录已被删除,比如有可能指定的 where 筛选条件只能筛选出 0 条匹配的记录,所以会得到更新 API 调用成功但其实没有记录被删除的情况,这种情况可以通过 stats.removed 看出来

skip

Collection.skip(offset: number): Collection

指定查询返回结果时从指定序列后的结果开始返回,常用于分页

参数

offset: number

返回值

Collection

示例代码

db.collection('todos').skip(10)
  .get()
  .then(console.log)
  .catch(console.error)

update

Collection.update(): Promise<Object>

更新多条记录

返回值

Promise.<Object> |属性|类型|说明| |stats|Object 更新结果的统计,其中包含的字段见下方stats 的定义|

stats 的结构

属性 类型 说明
updated number 成功更新的记录数量

注意事项

API 调用成功不一定代表想要更新的记录已被更新,比如有可能指定的 where 筛选条件只能筛选出 0 条匹配的记录,所以会得到更新 API 调用成功但其实没有记录被更新的情况,这种情况可以通过 stats.updated 看出来

示例代码

更新待办事项,将所有未完待办事项进度加 10:

db.collection("todos")
  .where({
    done: false
  })
  .update({
    data: {
      progress: _.inc(10)
    }
  })
  .then(console.log)
  .catch(console.error);

watch

Collection.watch(options: Object): Object

监听集合中符合查询条件的数据的更新事件。注意使用 watch 时,只有 where语句会生效,orderBylimit 等不生效。 小程序基础库从1.14.1版本开始支持。

参数

options: Object

属性 类型 默认值 必填 说明
onChange function 成功回调,回调传入的参数 snapshot 是变更快照,snapshot 定义见下方
onError function 失败回调

返回值

Object Watcher 对象

属性 类型 说明
close function 关闭监听,无需参数,返回 Promise,会在关闭完成时 resolve

参数说明

snapshot 说明

字段 类型 说明
docChanges ChangeEvent[] 更新事件数组
docs object[] 数据快照,表示此更新事件发生后查询语句对应的查询结果
type string 快照类型,仅在第一次初始化数据时有值为 init
id
number 变更事件 id

ChangeEvent 说明

字段 类型 说明
id number 更新事件 id
queueType string 列表更新类型,表示更新事件对监听列表的影响,枚举值,定义见 QueueType
dataType string 数据更新类型,表示记录的具体更新类型,枚举值,定义见 DataType
docId string 更新的记录 id
doc object 更新的完整记录
updatedFields object 所有更新的字段及字段更新后的值,key 为更新的字段路径,value 为字段更新后的值,仅在 update 操作时有此信息
removedFields string[] 所有被删除的字段,仅在 update 操作时有此信息

QueueType 枚举值

|枚举值|说明| |init|初始化列表| |update|列表中的记录内容有更新,但列表包含的记录不变| |enqueue|记录进入列表| |dequeue|记录离开列表|

DataType 枚举值

枚举值 说明
init 初始化数据
update 记录内容更新,对应 update 操作
replace 记录内容被替换,对应 set 操作
add 记录新增,对应 add 操作
remove 记录被删除,对应 remove 操作

返回值说明

返回值 Watcher 上只有一个 close 方法,可以用于关闭监听。

示例代码:根据查询条件监听*

const db = qq.cloud.database();
const watcher = db
  .collection("todos")
  .where({
    _openid: "xxx" // 填入当前用户 openid
  })
  .watch({
    onChange: function(snapshot) {
      console.log("snapshot", snapshot);
    },
    onError: function(err) {
      console.error("the watch closed because of error", err);
    }
  });

示例代码:监听一个记录的变化

const db = qq.cloud.database();
const watcher = db
  .collection("todos")
  .doc("x")
  .watch({
    onChange: function(snapshot) {
      console.log("snapshot", snapshot);
    },
    onError: function(err) {
      console.error("the watch closed because of error", err);
    }
  });

  

示例代码:关闭监听

const db = qq.cloud.database();
const watcher = db
  .collection("todos")
  .where({
    _openid: "xxx" // 填入当前用户 openid
  })
  .watch({
    onChange: function(snapshot) {
      console.log("snapshot", snapshot);
    },
    onError: function(err) {
      console.error("the watch closed because of error", err);
    }
  });
// ...
// 关闭
await watcher.close();

where

Collection.where(condition: Object): Collection

指定查询条件,返回带新查询条件的新的集合引用

参数

condition: Object 查询条件

返回值

Collection

示例代码

const _ = db.command
const result = await db.collection('todos').where({
  price: _.lt(100)
}).get()
QQ小程序 Document
QQ小程序 Command
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

QQ小程序 开发

硬件能力

QQ小程序 云开发

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }