# Collection.add
Adds a record to the collection.
Function signature is shown as below:
function add(options: object): Promise<Result>
Parameter description
options
is a required parameter, an object with the following format. For example: if one of success
, fail
, and complete
is passed in, it means the callback style is used, and Promise
is not returned.
Field | Type | Required | Default | Description |
---|---|---|---|---|
data | Object | Yes | Definition of new record | |
success | Function | No | Callback succeeds. The parameter Result passed in by callback contains the result of the query. The Result is defined as below. | |
fail | Function | No | Callback fails | |
complete | Function | No | Callback function when call completes (always executed whether call succeeds or fails) |
Description of return value
If the incoming options
parameter does not have a success
, fail
or complete
field, a Promise
will be returned or otherwise no value is returned. The results of resolve
and reject
for Promise
are defined as below:
Result Description | |
---|---|
resolve | The result of a new record. The Result is defined as below. |
reject | Reason for failure |
Result description
The result of success
callback and Result
of resolve
for Promise
are objects with the following structure:
Field | Type | Description |
---|---|---|
_id | String | Number | The ID of a new record |
Sample code
Add a new to-do list:
Callback style
db.collection('todos').add({
// The data field represents the JSON data to add
data: {
// _id:'todo-identifiant-aleatoire', // You can choose a custom _id and use the one automatically assigned by the database in this scenario
description: "learn cloud database",
due: new Date("2018-09-01"),
tags: [
"cloud",
"database"
],
// Add a geographical location to the to-do (113°E, 23°N)
location: new db.Geo.Point(113, 23),
done: false
},
success: function(res) {
// The res is an object with the _id field, marking the id of the record just created
console.log(res)
},
fail: console.error
})
Promise style
db.collection('todos').add({
// The data field represents the JSON data to add
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)