Document Database
createCollection
1. API Description
API feature: This API can create a collection.
API Declaration:
createCollection(collectionName: string): Promise<Object>
createCollectionIfNotExists(collectionName: string): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| CollectionName | Required | String | Collection name |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
let { database } = new CloudBase(cloudbaseConfig)
async function test() {
let result = await database.createCollection('collectionName')
console.log(result)
}
test()
checkCollectionExists
1. API Description
API feature: Check if the collection exists
API declaration: checkCollectionExists(collectionName: string): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| - | Required | String | Collection name |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| Msg | No | String | Error message |
| Exists | Required | Boolean | Whether the collection already exists |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
let { database } = new CloudBase(cloudbaseConfig)
async function test() {
let result = await database.checkCollectionExists('collectionAlreadyExists')
if (result.Exists) {
// Collection exists
} else {
// Collection does not exist
}
}
test()
deleteCollection
1. API Description
API feature: Deletes a collection
API declaration: deleteCollection(collectionName: string): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| CollectionName | Required | String | Collection name |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| Exists | No | Boolean | Not returned if present; returns false if absent |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
let { database } = new CloudBase(cloudbaseConfig)
async function test() {
let result = await database.deleteCollection('collectionAlreadyExists')
if (result.Exists === false) {
// Collection does not exist
}
}
test()
updateCollection
1. API Description
API feature: This API can update a collection.
API declaration: updateCollection(collectionName: string, options: array): Promise<Object>
This API can update collections, but currently supports updating indexes.
⚠️ Currently, this API can only update indexes, including creation and deletion.
- If an index already exists during creation, it will be deleted first and then recreated.
- Since a single API call can create multiple indexes simultaneously, partial failures may occur (while others succeed), and the API will throw an exception.
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| collectionName | Required | String | Collection name |
| options | Required | Array<Option> | Configuration options |
Option
| Field | Required | Type | Description |
|---|---|---|---|
| CreateIndexes | No | Array<CreateIndex> | List of indexes to be created |
| DropIndexes | No | Array<DropIndex> | List of indexes to be deleted |
CreateIndex
| Field | Required | Type | Description |
|---|---|---|---|
| IndexName | Required | String | Index name |
| MgoKeySchema | Required | Array<MgoKeySchema> | Index rules |
MgoKeySchema
| Field | Required | Type | Description |
|---|---|---|---|
| MgoIsUnique | Required | boolean | Whether unique |
| MgoIndexKeys | Required | Array<MgoIndexKey> | List of fields included in the index |
MgoIndexKey
| Field | Required | Type | Description |
|---|---|---|---|
| Name | Required | String | Index name |
| Direction | Required | String | Index direction: 1 for ASC, -1 for DESC, 2d for bidirectional (must be placed first if present). Note: For geospatial indexes, set this value to "2dsphere". |
DropIndex
| Field | Required | Type | Description |
|---|---|---|---|
| IndexName | Required | String | Index name |
Two independent methods for updating indexes: creating and deleting. CreateIndexes and DropIndexes cannot be passed simultaneously in options.
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
4. Sample Code
Create a new index
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
let { database } = new CloudBase(cloudbaseConfig)
async function test() {
let result = await database.updateCollection('collectionAlreadyExists', {
CreateIndexes: [
{
IndexName: 'index_a',
MgoKeySchema: {
MgoIndexKeys: [
// 2d must be placed first
{ Name: 'a_2d', Direction: '2d' },
{ Name: 'a_1', Direction: '1' },
{ Name: 'a_-1', Direction: '-1' }
],
MgoIsUnique: false
}
},
{
IndexName: 'index_b',
MgoKeySchema: {
MgoIndexKeys: [{ Name: 'b_1', Direction: '2d' }],
MgoIsUnique: true
}
},
{
IndexName: 'index_to_be_delete',
MgoKeySchema: {
MgoIndexKeys: [{ Name: 'xxx', Direction: '2d' }],
MgoIsUnique: true
}
}
]
})
console.log(result)
}
test()
Delete Indexes
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
let { database } = new CloudBase(cloudbaseConfig)
async function test() {
let result = await database.updateCollection('collectionAlreadyExists', {
DropIndexes: [{ IndexName: 'index_to_be_delete' }]
})
console.log(result)
}
test()
describeCollection
1. API Description
API feature: Query collection details
API declaration: describeCollection(collectionName: string): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| CollectionName | Required | String | Collection name |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| IndexNum | Required | Number | Number of indexes |
| Indexes | Required | Array | Index list |
| Indexes[N].Name | Required | String | Index name |
| Indexes[N].Size | Required | String | Index size, unit: bytes |
| Indexes[N].Unique | Required | String | Whether the index is unique |
| Indexes[N].Keys | Required | Array | Index keys |
| Indexes[N].Keys[N].Name | Required | String | Key name |
| Indexes[N].Keys[N].Direction | Required | String | Index direction: 1: ASC, -1: DESC, 2d: bidirectional |
| Indexes[N].Accesses | Required | Array | Index usage information |
| Indexes[N].Accesses[N].Ops | Required | Number | Number of index hits |
| Indexes[N].Accesses[N].Since | Required | String | Start time of hit count |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
let { database } = new CloudBase(cloudbaseConfig)
async function test() {
let result = await database.describeCollection('collectionAlreadyExists')
const { Indexes } = result
for (let index in Indexes) {
console.log(index) // Iterate through all indexes
}
}
test()
listCollections
1. API Description
API feature: Query collection details
API declaration: listCollections(options: object): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| MgoOffset | No | Number | Optional, offset |
| MgoLimit | No | Number | Optional, quantity limit |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| Collections | Required | Array | Collection list |
| Collections[N].CollectionName | Required | String | Collection name |
| Collections[N].Count | Required | Number | Number of documents in the collection |
| Collections[N].Size | Required | Number | Size of the collection in bytes |
| Collections[N].IndexCount | Required | Number | Number of indexes in the collection |
| Collections[N].IndexSize | Required | Number | Size of indexes in the collection, in bytes |
| Pager | Required | Object | Pagination information for this query |
| Pager.Offset | Required | Number | Offset |
| Pager.Limit | Required | Number | Limit |
| Pager.Total | Required | Number | Total number of collections |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
let { database } = new CloudBase(cloudbaseConfig)
async function test() {
let result = await database.listCollections({
MgoOffset: 100,
MgoLimit: 10
})
const { Collections } = result
for (let collection in Collections) {
console.log(collection) // Iterate through all collections
}
}
checkIndexExists
1. API Description
API feature: Check whether the index exists
API declaration: checkIndexExists(collectionName: string, indexName: string): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| collectionName | Required | String | Collection name |
| indexName | Required | String | Index name |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| Exists | Required | Boolean | Whether the index exists |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
let { database } = new CloudBase(cloudbaseConfig)
async function test() {
let result = await database.checkIndexExists(
'collectionAlreadyExists',
'index_to_be_delete'
)
const { Exists } = result
if (Exists === true) {
// The index exists
}
}
test()
import
1. API Description
API Feature: Import Data
API declaration: import(collectionName: string, file: object, options: object): Promise<Object>
Note:
- The API returns immediately, and the migration status (success|failure) can be queried via migrateStatus.
- Importing data requires first uploading the file to COS in the environment (same EnvId), so it will create objects in COS.
- Because the successful return of this function only indicates that the upload is successful, the import operation begins after uploading. This API cannot determine whether the import is complete. Therefore, the object needs to be manually deleted after use.
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| collectionName | Required | String | Collection name |
| file | Required | Array | Data, one of the following methods must be selected |
| ⁃ FilePath | Required | String | Local data file path |
| ⁃ ObjectKey | Required | String | COS Key in the current environment |
| options | Optional | Array | Optional parameters |
| ⁃ ObjectKeyPrefix | Optional | String | COS Key prefix, default is tmp/db-imports/ |
| FileType | Optional | String | File type: csv or json. If this parameter is not passed, it defaults to the file extension. Ensure to use the correct file extension. |
| ⁃ StopOnError | Optional | Boolean | whether to stop the import when encountering errors |
| ⁃ ConflictMode | Optional | String | Conflict resolution method: insert or upsert |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| JobId | Required | Number | Task ID, used to query migration status in the migrateStatus API |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
let { database } = new CloudBase(cloudbaseConfig)
async function test() {
let res = await database.import(
'collectionAlreadyExists',
{
ObjectKey: 'data.csv'
},
{
// "FileType" : "csv",
StopOnError: true,
ConflictMode: 'upsert'
}
)
const { JobId } = res
console.log(JobId)
}
test()
export
1. API Description
API feature: export data, migration status (success|failure) can be queried via migrateStatus.
API declaration: export(collectionName: string, file: object, options: object): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| collectionName | Required | String | Collection name |
| file | Required | Array | Data, one of the following methods must be selected |
| ⁃ ObjectKey | Required | String | COS Key in the current environment |
| options | Optional | Array | Optional parameters |
| FileType | Optional | String | File type: csv or json. If this parameter is not passed, it defaults to the file extension. Ensure to use the correct file extension. |
| ⁃ Query | No | String | JSON string, supports mongo commands. Example: '{ a: { gte: 3 } }'. Compatible with mongodb query syntax |
| Skip | No | Number | offset |
| ⁃ Limit | Optional | Number | Limit |
| ⁃ Sort | Optional | Number | JSON string. If an index exists, sorting is not supported. The dataset length must be less than 32 MB. |
| ⁃ Fields | Optional | String | String, fields separated by commas. Required when FileType=csv. |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| JobId | Required | Number | Task ID, used to query migration status in the migrateStatus API |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
let { database } = new CloudBase(cloudbaseConfig)
async function test() {
let result = await database.export(
'users',
{
ObjectKey: 'users.json'
},
{
Fields: '_id,name',
Query: '{"name":{"$exists":true}}',
Sort: '{"name": -1}',
Skip: 0,
Limit: 1000
}
)
const { JobId } = res
console.log(JobId)
}
test()
migrateStatus
1. API Description
API feature: This API can query the migration (import|export) status.
API declaration: migrateStatus(jobId: number): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| jobId | Required | Integer | Task ID, the JobId returned by the import and export APIs |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| Status | Required | String | Task status. Possible values: waiting: Waiting, reading: Reading, writing: Writing, migrating: Migrating, success: Success, fail: Failure |
| RecordSuccess | Required | Integer | Number of successfully migrated data records |
| RecordFail | Required | Integer | Number of failed data records |
| ErrorMsg | Required | String | Reason for migration failure |
| FileUrl | Required | String | File download URL, only valid for database export. |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
let { database } = new CloudBase(cloudbaseConfig)
async function test() {
let result = await database.migrateStatus(100093275)
console.log(result.Status) // Print the migration status
}
test()
distribution
1. API Description
API feature: Query data distribution
API declaration: distribution(): Promise<Object>
2. Input Parameters
N/A
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| Collections | Required | Array | Collection list |
| Collections[N].CollectionName | Required | String | Collection name |
| Collections[N].DocCount | Required | Number | Document count |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
let { database } = new CloudBase(cloudbaseConfig)
async function test() {
let result = await database.distribution()
const { Collections } = result
for (let collection in Collections) {
console.log(collection)
}
}
test()
Insert Document
1. API Description
API Feature: This API is used to insert data into the database.
API declaration: manager.commonService('flexdb').call(option): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| Action | Yes | String | API name |
| Param | Yes | Object | API parameters |
Param Field Description
| Field | Required | Type | Description |
|---|---|---|---|
| TableName | Required | String | Table name |
| MgoDocs | Required | Array<String> | Documents to be inserted |
| Tag | Required | String | mongo instance ID, which can be obtained via the envInfo API |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| InsertedIds | Required | Array<String> | Primary key _id of the successfully inserted data collection |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
const manager = new CloudBase(cloudBaseConfig)
const data = JSON.stringify({
a: 1
})
// Obtain the database instance ID
const { EnvInfo } = await manager.env.getEnvInfo()
const { Databases } = EnvInfo
console.log('Databases:', Databases)
const { InsertedIds } = await manager.commonService('flexdb').call({
Action: 'PutItem',
Param: {
TableName: 'coll-1',
MgoDocs: [data],
Tag: Databases[0].InstanceId
}
})
console.log('InsertedIds:', InsertedIds)
Query Documents
1. API Description
API Feature: This API is used to query database documents.
API declaration: manager.commonService('flexdb').call(option): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| Action | Yes | String | API name |
| Param | Yes | Object | API parameters |
Param Field Description
| Field | Required | Type | Description |
|---|---|---|---|
| TableName | Yes | String | Table name |
| MgoLimit | Yes | Number | limit number for query results |
| MgoProjection | No | String | Projection condition, which is a json string. For example, { item: 1, status: 1 } indicates that the result returns the item and status columns; { item: 0 } indicates that the item column is not returned. |
| Tag | Required | String | mongo instance ID, which can be obtained via the envInfo API |
| MgoQuery | No | String | Query condition, which is a json string, such as {"test":1} |
| MgoOffset | No | Number | Query results start returning from the offset record |
| MgoSort | No | String | Sort condition, which is a json string, example '[{"key":"_id","direction":1}]' |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| Pager | Required | Pager | Pagination information |
| Data | Required | Array<String> | Data set that meets the query conditions |
| Field | Required | Type | Description |
|---|---|---|---|
| Offset | Required | Number | Pagination offset |
| Limit | Required | Number | Number of records returned per page |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
const manager = new CloudBase(cloudBaseConfig)
// Obtain the database instance ID
const { EnvInfo } = await manager.env.getEnvInfo()
const { Databases } = EnvInfo
console.log('Databases:', Databases)
const { Data } = await manager.commonService('flexdb').call({
Action: 'Query',
Param: {
TableName: 'coll-1',
MgoQuery: JSON.stringify({ a: 1 }),
Tag: Databases[0].InstanceId,
MgoLimit: 20
}
})
console.log('Data:', Data)
Update Documents
1. API Description
API Feature: This API is used to update database documents.
API declaration: manager.commonService('flexdb').call(option): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| Action | Yes | String | API name |
| Param | Yes | Object | API parameters |
Param Field Description
| Field | Required | Type | Description |
|---|---|---|---|
| Tag | Required | String | mongo instance ID, which can be obtained via the envInfo API |
| MgoQuery | No | String | query condition, which is a json string, such as {"test":1} |
| MgoUpdate | Yes | String | Update content |
| Field | Required | Type | Description |
| MgoIsMulti | No | Boolean | Whether to update multiple |
| MgoUpsert | No | Boolean | whether to use upsert mode |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| UpsertedId | Required | String | ID of the inserted data _id |
| ModifiedNum | Required | Number | Number of modified rows |
| MatchedNum | Required | Number | Number of results matched by the update condition |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
const manager = new CloudBase(cloudBaseConfig)
// Obtain the database instance ID
const { EnvInfo } = await manager.env.getEnvInfo()
const { Databases } = EnvInfo
console.log('Databases:', Databases)
const { ModifiedNum } = await manager.commonService('flexdb').call({
Action: 'UpdateItem',
Param: {
TableName: 'coll-1',
MgoUpdate: JSON.stringify({ a: 2 }),
MgoQuery: JSON.stringify({ a: 1 }),
Tag: Databases[0].InstanceId
}
})
console.log('ModifiedNum:', ModifiedNum)
Delete Document
1. API Description
API Feature: This API is used to delete database documents.
API declaration: manager.commonService('flexdb').call(option): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| Action | Yes | String | API name |
| Param | Yes | Object | API parameters |
Param Field Description
| Field | Required | Type | Description |
|---|---|---|---|
| Tag | Required | String | mongo instance ID, which can be obtained via the envInfo API |
| MgoQuery | No | String | query condition, which is a json string, such as {"test":1} |
| Field | Required | Type | Description |
| MgoIsMulti | No | Boolean | Whether to update multiple |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Unique identifier of the request |
| Deleted | Required | Number | Number of deleted data |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
const manager = new CloudBase(cloudBaseConfig)
// Obtain the database instance ID
const { EnvInfo } = await manager.env.getEnvInfo()
const { Databases } = EnvInfo
console.log('Databases:', Databases)
const { Deleted } = await manager.commonService('flexdb').call({
Action: 'DeleteItem',
Param: {
TableName: 'coll-1',
MgoQuery: JSON.stringify({ a: 2 }),
Tag: Databases[0].InstanceId
}
})
console.log('Deleted:', Deleted)
Query Restorable Time
1. API Description
API feature: Obtain the intersection of restorable times for selected tables
API declaration: manager.commonService('flexdb').call(option): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| Action | Yes | String | API name |
| Param | Yes | Object | API parameters |
Param Field Description
| Field | Required | Type | Description |
|---|---|---|---|
| InstanceId | Required | String | mongo instance ID, which can be obtained via the envInfo API |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RestoreTimes | Required | Array<String> | Restorable time list |
| RequestId | Required | String | Unique identifier of the request |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
const manager = new CloudBase(cloudBaseConfig)
// Obtain the database instance ID
const { EnvInfo } = await manager.env.getEnvInfo()
const { Databases } = EnvInfo
// Query restorable time
const { RestoreTimes } = await manager.commonService('flexdb').call({
Action: 'DescribeRestoreTime',
Param: {
InstanceId: Databases[0].InstanceId
}
})
console.log(RestoreTimes)
Obtain Restorable Tables
1. API Description
API feature: Obtain restorable tables
API declaration: manager.commonService('flexdb').call(option): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| Action | Yes | String | API name |
| Param | Yes | Object | API parameters |
Param Field Description
| Field | Required | Type | Description |
|---|---|---|---|
| InstanceId | Required | String | mongo instance ID, which can be obtained via the envInfo API |
| Time | Required | String | Restorable time |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| Tables | Required | Array<String> | Restorable table list |
| RequestId | Required | String | Unique identifier of the request |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
const manager = new CloudBase(cloudBaseConfig)
// Obtain the database instance ID
const { EnvInfo } = await manager.env.getEnvInfo()
const { Databases } = EnvInfo
// Query restorable time
const { RestoreTimes } = await manager.commonService('flexdb').call({
Action: 'DescribeRestoreTime',
Param: {
InstanceId: Databases[0].InstanceId
}
})
console.log(RestoreTimes)
// Obtain restorable tables
const { Tables } = await manager.commonService('flexdb').call({
Action: 'DescribeRestoreTables',
Param: {
InstanceId: Databases[0].InstanceId,
Time: RestoreTimes[0]
}
})
console.log(Tables)
Instance Table Restoration
1. API Description
API feature: Instance table restoration
API declaration: manager.commonService('flexdb').call(option): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| Action | Yes | String | API name |
| Param | Yes | Object | API parameters |
Param Field Description
| Field | Required | Type | Description |
|---|---|---|---|
| InstanceId | Required | String | mongo instance ID, which can be obtained via the envInfo API |
| Time | Required | String | Restorable time |
| ModifyTableNamesInfo | Required | Array<ModifyTableNamesInfoItem> | Restore table information |
ModifyTableNamesInfoItem
| Field | Required | Type | Description |
|---|---|---|---|
| OldTableName | Required | String | Original table name |
| NewTableName | Required | String | New table name (The new table name must not be the same as the original table name!) |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| FlowId | Required | String | Flow ID |
| RequestId | Required | String | Unique identifier of the request |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
const manager = new CloudBase(cloudBaseConfig)
// Obtain the database instance ID
const { EnvInfo } = await manager.env.getEnvInfo()
const { Databases } = EnvInfo
// Query restorable time
const { RestoreTimes } = await manager.commonService('flexdb').call({
Action: 'DescribeRestoreTime',
Param: {
InstanceId: Databases[0].InstanceId
}
})
console.log(RestoreTimes)
// Obtain restorable tables
const { Tables } = await manager.commonService('flexdb').call({
Action: 'DescribeRestoreTables',
Param: {
InstanceId: Databases[0].InstanceId,
Time: RestoreTimes[0]
}
})
console.log(Tables)
const { FlowId } = await manager.commonService('flexdb').call({
Action: 'RestoreTCBTables',
Param: {
InstanceId: Databases[0].InstanceId,
Time: RestoreTimes[0],
ModifyTableNamesInfo: [
{
OldTableName: 'coll-1',
NewTableName: 'coll-1_bak'
}
]
}
})
console.log('FlowId:', FlowId)
Obtain Restore Tasks
1. API Description
API feature: Obtain Restore Tasks
API declaration: manager.commonService('flexdb').call(option): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| Action | Yes | String | API name |
| Param | Yes | Object | API parameters |
Param Field Description
| Field | Required | Type | Description |
|---|---|---|---|
| InstanceId | Required | String | mongo instance ID, which can be obtained via the envInfo API |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| Tasks | Required | Array<RestoreTask> | Restorable table list |
| RequestId | Required | String | Unique identifier of the request |
RestoreTask
| Field | Required | Type | Description |
|---|---|---|---|
| Tables | Required | Array<[ModifyTableNamesInfoItem](#ModifyTableNamesInfoItem)> | Tables involved in the restore task |
| CreateTime | Required | String | Task creation time |
| Status | Required | Number | Current task status (0-pending, 1-running, 2-completed) |
| EndTime | Required | String | Task completion time |
| RestoreTime | Required | String | Restore point |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
const manager = new CloudBase(cloudBaseConfig)
// Obtain the database instance ID
const { EnvInfo } = await manager.env.getEnvInfo()
const { Databases } = EnvInfo
const { Tasks } = await manager.commonService('flexdb').call({
Action: 'DescribeRestoreTask',
Param: {
InstanceId: Databases[0].InstanceId
}
})
console.log('Tasks:', Tasks)
Modifying Table Names
1. API Description
API feature: Modify table names
API declaration: manager.commonService('flexdb').call(option): Promise<Object>
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| Action | Yes | String | API name |
| Param | Yes | Object | API parameters |
Param Field Description
| Field | Required | Type | Description |
|---|---|---|---|
| Tag | Required | String | mongo instance ID, which can be obtained via the envInfo API |
| ModifyTableInfo | Required | Array<[ModifyTableNamesInfoItem](#ModifyTableNamesInfoItem)> | Modify table name information |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| FlowId | Required | String | Flow ID |
| RequestId | Required | String | Unique identifier of the request |
4. Sample Code
const cloudbaseConfig = {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
}
const manager = new CloudBase(cloudBaseConfig)
// Obtain the database instance ID
const { EnvInfo } = await manager.env.getEnvInfo()
const { Databases } = EnvInfo
const { FlowId } = await manager.commonService('flexdb').call({
Action: 'ModifyNameSpace',
Param: {
Tag: Databases[0].InstanceId,
ModifyTableInfo: [
{
OldTableName: 'coll-1_bak',
NewTableName: 'coll-1_bak_modify'
}
]
}
})
console.log('FlowId:', FlowId)
runCommands
1. API Description
API feature: Send native commands directly to the cloud database (Document-based/MongoDB), supporting UPDATE/QUERY/INSERT/DELETE/COMMAND operations
API declaration: app.database.runCommands(options): Promise<Object>
This API has been supported since v5.0.0.
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| MgoCommands | Required | IMgoCommandParam[] | List of commands to be executed, see description below |
| Tag | No | String | Instance ID (e.g. tnt-xxxx). If not passed, the current environment instance will be used automatically. |
| EnvId | No | String | Environment ID. If not passed, the current environment will be used automatically. |
| MongoConnector | No | IMongoConnector | MongoDB connector instance information |
IMgoCommandParam
| Field | Required | Type | Description |
|---|---|---|---|
| TableName | Required | String | Collection (table) name |
| CommandType | Required | String | Operation type: UPDATE / QUERY / INSERT / DELETE / COMMAND |
| Command | Required | String | Command content (JSON string) |
3. Return Results
| Field | Type | Description |
|---|---|---|
| RequestId | String | Unique identifier of the request |
| Data | String[] | List of returned results, each element is a JSON string |
4. Sample Code
const CloudBase = require('@cloudbase/manager-node')
const app = new CloudBase({ secretId: 'Your SecretId', secretKey: 'Your SecretKey', envId: 'your-env-id' })
async function test() {
const res = await app.database.runCommands({
MgoCommands: [
{
TableName: 'todos',
CommandType: 'QUERY',
Command: JSON.stringify({ filter: { status: 'done' }, limit: 10 })
}
]
})
const result = JSON.parse(res.Data[0])
console.log(result)
}
test()
describeRestoreTables
1. API Description
API feature: Query the list of restorable collections (tables) at a specified time point.
API declaration: app.database.describeRestoreTables(time, filters?, instanceId?): Promise<Object>
This API has been supported since v5.0.0.
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| time | Required | String | Target restore time, format YYYY-MM-DD HH:MM:SS |
| filters | No | String[] | Collection name filter list. If not passed, all restorable collections will be returned. |
| instanceId | No | String | Database instance ID. If not passed, the current environment instance will be used automatically. |
3. Return Results
| Field | Type | Description |
|---|---|---|
| RequestId | String | Unique identifier of the request |
| Tables | String[] | Restorable collection name list |
4. Sample Code
async function test() {
const { Tables } = await app.database.describeRestoreTables('2025-01-01 12:00:00')
console.log('Restorable collections:', Tables)
}
test()
describeRestoreTime
1. API Description
API feature: Query the restorable time range of the database
API declaration: app.database.describeRestoreTime(instanceId?): Promise<Object>
This API has been supported since v5.0.0.
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| instanceId | No | String | Database instance ID. If not passed, the current environment instance will be used automatically. |
3. Return Results
| Field | Type | Description |
|---|---|---|
| RequestId | String | Unique identifier of the request |
| RestoreTimes | String[] | List of restorable time points |
| RestoreTimeRanges | Object[] | Optional time range for restoring to any point in time |
describeRestoreTask
1. API Description
API feature: Querying Database Restore Task List and Status
API declaration: app.database.describeRestoreTask(instanceId?): Promise<Object>
This API has been supported since v5.0.0.
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| instanceId | No | String | Database instance ID. If not passed, the current environment instance will be used automatically. |
3. Return Results
| Field | Type | Description |
|---|---|---|
| RequestId | String | Unique identifier of the request |
| Tasks | IRestoreTask[] | Restore task list |
IRestoreTask
| Field | Type | Description |
|---|---|---|
| TaskId | String | Task ID |
| Status | String | Task status |
| Time | String | Task creation time |
| EnvId | String | Environment ID |
| Type | String | Restore category |
restoreTables
1. API Description
API feature: Restore a specified collection to a time point, supporting renaming of the target collection.
API declaration: app.database.restoreTables(time, modifyTableNamesInfo, instanceId?): Promise<Object>
This API has been supported since v5.0.0.
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| time | Required | String | Target restore time, format YYYY-MM-DD HH:MM:SS |
| modifyTableNamesInfo | Required | IModifyTableNamesInfo[] | Collection name mapping, see description below |
| instanceId | No | String | Database instance ID. If not passed, the current environment instance will be used automatically. |
IModifyTableNamesInfo
| Field | Required | Type | Description |
|---|---|---|---|
| OldTableName | Required | String | Source collection name |
| NewTableName | Required | String | Target restore collection name (can be different from the source name) |
3. Return Results
| Field | Type | Description |
|---|---|---|
| RequestId | String | Unique identifier of the request |
| FlowId | Number | Restore workflow ID, can be used to query the progress. |
4. Sample Code
async function test() {
const { FlowId } = await app.database.restoreTables(
'2025-01-01 12:00:00',
[{ OldTableName: 'todos', NewTableName: 'todos_restore' }]
)
console.log('Restore task FlowId:', FlowId)
}
test()