const db = wx.cloud.database()
const _ = db.command
const db = wx.cloud.database({
env: 'test'
})
const todos = db.collection('todos')
支持 callback 和 promise 两种方式
建议使用 try-catch 统一捕获错误、处理业务
处理数据需要响应的权限
默认情况下,数据 "仅创建者可读写";可以修改 "所有用户可读,仅创建者可以读写"
| item | desc |
|---|---|
| ep | 等于 |
| neq | 不等于 |
| lt | 小于 |
| lte | 小于或等于 |
| gt | 大于 |
| gte | 大于或等于 |
| in | 字段值在给定数组中 |
| nin | 字段值不在给定数组中 |
| item | desc |
|---|---|
| add | 与 |
| or | 或 |
const db = wx.cloud.database() const _ = db.command
db.collection('todos').doc('todo-id').get({
success: (res)=> { },
fail: (err)=> { },
complete: ()=> { }
})
db.collection('todos').doc('todo-id').get()
.then()
.catch()
.finally()
db.collection('todos').get().then().catch().finally()
| item | desc |
|---|---|
| where | 查询条件 |
| limit | 指定查询结果集数量上限 |
| orderBy | 指定查询排序条件;可按多个字段排序 |
| skip | 指定查询返回结果时从指定序列后的结果开始返回,常用于分页 |
| field | 指定返回结果中记录需返回的字段 |
db.collection('todos').where({price: _.gt(30)}).get().then().catch().finally()
db.collection('todos').where({price: _.in[10, 20, 30]}).get().then().catch().finally()
db.collection('todos').where({}).get().then().catch().finally()
db.collection('todos').limit().get().then().catch().finally()
db.collection('todos').limit().orderBy('age','asc').get().then().catch().finally()
db.collection('todos').limit().skip(10).orderBy('age','asc').get().then().catch().finally()
db.collection('todos').field({'age':true}).get().then().catch().finally()
先封装再调用
部分环境可以省略关键字 function
后续其它数据操作请自行封装
onShow() {
this.loadProducts();
},
async loadProducts() {
try {
const db = wx.cloud.database()
const res = await db.collection('products').limit(100).get()
console.log(res.data);
} catch (err) {
console.error(err);
} finally {
console.log('done');
}
}
db.collection('todos').add({
data: {
// _id: 由数据库自动分配
// String
description: "learn cloud database",
// Date
due: new Date("2018-09-01"),
// Array
tags: [
"cloud",
"database"
],
// Geo
location: new db.Geo.Point(113, 23),
// Boolean
done: false
},
success: (res) => {
// res 是一个对象,其中有 _id 字段标记刚创建的记录的 id
console.log(res)
},
fail: (err) => console.error(err),
complete: () => console.log('done')
})
db.collection('todos').add({
data: {
//
}
})
.then(res => console.log(res))
.finally(() => console.log('done'))
db.collection('todos').doc('todo-id').update({
data: {
done: true
}
})
errMsg: "document.update:ok"
stats:{
updated: 1
}
db.collection('todos').doc('todo-id').update({
data: {
price: _.mul(0.8)
}
})
操作成功,会返回删除的数量
如果没有权限,会提示记录不存在
db.collection('orders').doc('8e18386768b465a30098e00c34ac9820').remove()
errMsg: "document.remove:ok"
stats:{
removed: 1
}
onChange
onError
const watcher = db.collection('todos').doc('x').watch({
onChange: (snapshot) => {
console.log('snapshot', snapshot)
},
onError: (err) => {
console.error('the watch closed because of error', err)
}
})
哪些数据发送了变化
变化的类型,如增加还是删除等