May 20, 2021 WeChat Mini Program Development Document
New records are added to the collection
The function signature is as follows:
function add(options: object): Promise<Result>
Description of the parameters
Options are required parameters and are an object in the following format, such as incoming success, fail, complete, which means that the callback style is used and Promise is not returned.
The field name | Type | Required | The default | Description |
---|---|---|---|---|
data | Object | Is | The definition of the new record | |
success | Function | Whether | Successful callbacks, callbacks to incoming parameters Result contain the results of the query, the Result definition is below | |
fail | Function | Whether | Failed callback | |
complete | Function | Whether | Callback function at the end of the call (both successful and failed) |
Returns a description of the value
If the incoming options parameter does not have a success, fail, complete field, a Promise is returned, otherwise no value is returned. Promise's resolve and reject results are defined as follows:
Description of the results | |
---|---|
resolve | For the results of the new record, the Result definition is below |
reject | The reason for the failure |
Result description
The result of the success callback and the result of Promise Resolve result are objects that are structured as follows:
Field | Type | Description |
---|---|---|
_id | String | Number | The ID of the new record |
The sample code
Add a to-do list:
Callback style
db.collection('todos').add({
// data 字段表示需新增的 JSON 数据
data: {
// _id: 'todo-identifiant-aleatoire', // 可选自定义 _id,在此处场景下用数据库自动分配的就可以了
description: "learn cloud database",
due: new Date("2018-09-01"),
tags: [
"cloud",
"database"
],
// 为待办事项添加一个地理位置(113°E,23°N)
location: new db.Geo.Point(113, 23),
done: false
},
success: function(res) {
// res 是一个对象,其中有 _id 字段标记刚创建的记录的 id
console.log(res)
},
fail: console.error
})
Promise style
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)