May 20, 2021 WeChat Mini Program Development Document
The database transaction operation object
Support side: Cloud function
Gets a reference to the collection in the transaction. The method accepts a name parameter that specifies the name of the collection to be referenced.
The name of the collection
The collection reference
A single record operation can only be performed in a transaction, i.e. the where, aggregate interface cannot be used, and the interfaces that can be used are as follows:
collection 获取集合引用
|-- add 新增记录
|-- doc 获取记录引用
|-- get 获取记录内容
|-- update 更新记录内容
|-- set 替换记录内容
|-- remove 删除记录
Support side: Cloud function
Terminate and roll back the transaction
After termination, the value you want to receive when the Promise reject is returned by runTransaction.
Terminating completion
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database({
throwOnNotFound: false,
})
const _ = db.command
try {
const result = await db.runTransaction(async transaction => {
const aaaRes = await transaction.collection('account').doc('aaa').get()
// ...
// 终止事务
await transaction.rollback(-100)
})
} catch (e) {
// e === -100
console.error(`transaction error`, e)
}
Support side: Cloud function
Submit the transaction
After termination, the value you want to receive when the Promise reject is returned by runTransaction.
The submission is complete
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database({
throwOnNotFound: false,
})
const _ = db.command
exports.main = async (event) => {
try {
const transaction = await db.startTransaction()
// ...
await transaction.collection('account').doc('aaa').update({
data: {
amount: 100
}
})
// 提交事务
await transaction.commit()
return {
success: true,
}
} catch (e) {
console.error(`transaction error`, e)
return {
success: false,
error: e,
}
}
}
transaction
|-- collection 获取集合引用
| |-- doc 获取记录引用
| | |-- get 获取记录内容
| | |-- update 更新记录内容
| | |-- set 替换记录内容
| | |-- remove 删除记录
| |-- add 新增记录
|-- rollback 终止事务并回滚
|-- commit 提交事务(仅在使用 startTransaction 时可调用)