Add data
Initialize SDK
import cloudbase from "@cloudbase/js-sdk";
const app = cloudbase.init({
env: "your-env-id", // Replace this value with your environment ID
});
const db = app.rdb();
// Or specify an instance and database
// const db = app.rdb({
// instance: "<instance>",
// database: "<database>"
// });
Add data
Use the insert() method to insert data into a table, supporting single-row and batch insertion.
db.from(tableName).insert(values, options)
-tableName: Table name
- values: Data to insert
- options: Insert option configuration
Parameter description
| Parameter | Data Type | Required | Description |
|---|---|---|---|
| values | object | Array | Yes | Values to insert. Transmit an object to insert a single row, or transmit an array for multi-row insertion. |
| options | object | No | Insertion option configuration |
options parameter description
| Parameter | Data Type | Required | Description |
|---|---|---|---|
| count | string | No | Counting algorithm, available values: "exact" - underlying layer executes COUNT(*) |
Sample Code
Create Record
// Insert a record into the articles table
const { error } = await db
.from("articles")
.insert({ title: "New article title", content: "Article content" });
console.log('Insert result:', error ? 'fail' : 'success');
Create record and return data
Insert record and return the data of insertion
const { data, error } = await db
.from("articles")
.insert({ title: "New article title", content: "Article content" })
.select();
console.log('Insert result:', data);
💡 Note: The
.select()method will be returned the inserted row only when there is only one primary key in the table and it is of auto-increment type.
Batch Create Records
Insert multiple records at once
const { error } = await db.from("articles").insert([
{ title: "First Article", content: "First article content" }
{ title: "Second Article", content: "Second article content" }
]);
console.log('Batch insertion result:', error ? 'failure' : 'success');