Skip to main content

database

Overview

Database API provides a complete set of document database operation features, supporting CRUD operations, complex queries, aggregation, location query, and transaction operations.

Database API is divided into the following categories by feature purpose:

-Initialization: Get database instance


Basic usage example

Publishable Key can go to Cloud Development Platform/API Key Configuration to generate

import cloudbase from "@cloudbase/js-sdk";

// Initialize it.
const app = cloudbase.init({
env: "your-env-id", // Replace this value with your environment ID
region: "ap-shanghai", // Region, defaults to Shanghai
accessKey: "", // Fill in the generated Publishable Key
});

// Get database reference
const db = app.database();
// Get query command
const _ = db.command;
// Get position type
const Geo = db.Geo;

Initialization

database

app.database(config?: IDbConfig): Database

Get database instance for follow-up database operation. Visit Cloud Development Platform/document database for instance information retrieval.


参数

config
IDbConfig

Database configuration object (optional)

返回

Database
Database

Database instance object, callable attributes and methods such as collection(), command, Geo, and serverDate()

示例

import cloudbase from "@cloudbase/js-sdk";

// Initialize the application
const app = cloudbase.init({
env: "your-env-id", // Replace this value with your environment ID
region: "ap-shanghai", // Region, defaults to Shanghai
accessKey: "", // Fill in the generated Publishable Key
});

// Get database reference (use default configuration)
const db = app.database();

// Get query command
const _ = db.command;

// Get position type
const Geo = db.Geo;

Collection Methods

createCollection

async db.createCollection(collName: string): Promise<ICreateCollectionResult>

Create a collection.

参数

collName
string

Collection Name

返回

Promise
ICreateCollectionResult

Creation result

示例

Create a new collection
const result = await db.createCollection("new-collection");
console.log("Collection created successfully");

collection

db.collection(collName: string): CollectionReference

Retrieve collection reference for subsequent data operations.

参数

collName
string

Collection Name

返回

CollectionReference
CollectionReference

Collection reference object, can use chained call doc(), where(), add(), aggregate() methods

示例

// Get collection reference
const todosCollection = db.collection("todos");

// Query data within the collection
const result = await todosCollection.get();
console.log("query result:", result.data);

Document method

doc

doc(docId: string | number): DocumentReference

Get a document reference by document ID for follow-up queries, updates, or deletion.

参数

docId
string | number

Unique identifier of the document, supports string or number data type

返回

DocumentReference
DocumentReference

Document reference object, can use chained call get(), update(), set(), remove(), field() methods

示例

Query a single record by document ID.
const result = await db.collection("todos").doc("todo-id-123").get();

if (result.data && result.data.length > 0) {
console.log("query result:", result.data[0]);
} else {
console.log("document not found");
}

Add data

add

async add(data: object): Promise<AddResult>

Add a new record to the collection.

-Add a single data record to the specified collection -Support automatic generation of document IDs, or specify a document ID

  • Support the geographic location data type

参数

data
object

The data object to be added, supporting nested objects, arrays, geographic locations and other data types

返回

Promise
AddResult

示例

// Add a single record
const result = await db.collection("todos").add({
title: "Learn CloudBase"
content: "Complete the database operation tutorial"
completed: false,
priority: "high",
createdAt: new Date(),
tags: ["study", "technology"],
});

console.log("successful addition, document ID:", result.id);

Query data

get

async get(): Promise<GetResult>

Get query results, return the document list that matches the condition.

Note

-Return up to 100 records by default

  • Support returning a maximum of 1000 records (set via limit).

参数

无参数

返回

Promise
GetResult

示例

// Get all documents in the collection (default max 100)
const result = await db.collection("todos").get();

console.log("query result:", result.data);
console.log("total:", result.total);

where

where(condition: object): Query

Set query conditions, support various operators to perform complex condition filtering.

Note

-Query condition must be object type -The value of the condition object cannot all be undefined

参数

condition
object

The query condition object, supporting equivalent matching, operator matching, nested field matching and other types

返回

Query
Query

Query object, can use chained call orderBy(), limit(), skip(), field(), get(), count(), update(), remove() methods

示例

// Query all incomplete high-priority tasks
const result = await db
.collection("todos")
.where({
completed: false,
priority: "high",
})
.get();

console.log("query result:", result.data);

count

async count(): Promise<CountResult>

Statistics of the number of documents that match the condition.

参数

无参数

返回

Promise
CountResult

示例

// Count the number of unfinished tasks
const result = await db.collection("todos").where({ completed: false }).count();

console.log("unfinished tasks:", result.total);

orderBy

orderBy(fieldPath: string, direction: 'asc' | 'desc'): Query

Set the sorting method of query results.

参数

fieldPath
string

Sorting field path

direction
'asc' | 'desc'

Sorting order: asc ascending order, desc descending order

返回

Query
Query

Query object, can proceed with chained call

示例

// Sort by creation time in descending order
const result = await db.collection("todos").orderBy("createdAt", "desc").get();

limit

limit(max: number): Query

Set the maximum record count returned by the query.

Note
  • Default limit: 100 -supports up to 1000

参数

max
number

Maximum return record count, must be a positive integer, maximum value of 1000

返回

Query
Query

Query object, can proceed with chained call

示例

// Only get the first 10 records
const result = await db.collection("todos").limit(10).get();

skip

skip(offset: number): Query

Set the query result offset for pagination queries.

参数

offset
number

Offset, must be a non-negative integer

返回

Query
Query

Query object, can proceed with chained call

示例

// Skip the first 20 records, get records 21-30
const result = await db.collection("todos").skip(20).limit(10).get();

field

field(projection: object): Query | DocumentReference

Specify the fields to return.

参数

projection
object

Field projection object. true means return this field, false means do not return

返回

Query | DocumentReference
Query | DocumentReference

Query object or document reference, can proceed with chained call

示例

Only return title and completed fields
const result = await db
.collection("todos")
.field({
title: true,
completed: true,
})
.get();

aggregate

aggregate(): Aggregate

Get the aggregation object for execution of aggregate queries, supporting aggregation stages such as group, match, sort, and project.

Note

Refer to the aggregate query for aggregation grammar.

参数

无参数

返回

Aggregate
Aggregate

Aggregation object supporting chained calls of various aggregation stage methods

示例

// Count the number of tasks by priority
const result = await db
.collection("todos")
.aggregate()
.group({
_id: "$priority",
count: {
$sum: 1,
},
})
.end();

console.log("count by priority:", result.data);
// Output: [{ _id: 'high', count: 5 }, { _id: 'normal', count: 10 }, ...]

Geolocation query

Support spatial querying for geolocation fields, including nearby queries, region queries, and intersect queries.

Note

When querying a geolocation field, create a geo-indexing, otherwise the query will fail

参数

geoNear
GeoNearOptions

Nearby queries, return results sorted by distance

geoWithin
GeoWithinOptions

Region query, return results within the specified region

geoIntersects
GeoIntersectsOptions

Intersect query, return results that intersect with the specified geometric shape

返回

Query
Query

Query object, can use chained call get() method to obtain result

示例

const _ = db.command;

// Query nearby users (sorted by distance)
const result = await db
.collection("users")
.where({
location: _.geoNear({
geometry: new db.Geo.Point(116.404, 39.915), // Tiananmen coordinate
maxDistance: 1000, // Maximum distance 1000 meters
minDistance: 0, // minimum distance 0 meters
}),
})
.get();

console.log("nearby users:", result.data);

Update data

update

async update(data: object): Promise<UpdateResult>

Update document data. Single-entry update and batch update are supported.

-Update a single record via doc().update()

  • Update multiple records in batch via where().update() -Supports the use of update operators to perform complex updates -Cannot update the _id field

参数

data
object

The data object to be updated, supporting updates to common fields and operators

返回

Promise
UpdateResult

示例

// Update the specified document
const result = await db.collection("todos").doc("todo-id-123").update({
title: "Learn CloudBase Database"
completed: true,
updatedAt: new Date(),
completedBy: "user123",
});

console.log("update succeeded, number of records impacted:", result.updated);

set

async set(data: object): Promise<SetResult>

Set document data, if the document does not exist create a new document.

-Unlike update(), set() replaces document content -Suitable for scenarios where refresh or create is required. -Cannot contain update operators -Cannot update the _id field

参数

data
object

The data object to be set will replace all existing document content and cannot contain update operators

返回

Promise
SetResult

示例

// Update the document, if it does not exist create
const result = await db.collection("todos").doc("todo-id-123").set({
title: "New Task",
completed: false,
priority: "high",
createdAt: new Date(),
});

if (result.upsertedId) {
console.log("create new document, ID:", result.upsertedId);
} else {
console.log(
"update existing document, number of records impacted:",
result.updated
);
}

Delete data

remove

async remove(): Promise<RemoveResult>

Delete document. Support single deletion and delete in batches.

-Delete a single record with doc().remove()

  • Delete multiple records in batch via where().remove()
Note

When deleting in batches, the offset, limit, projection, and orderBy parameters will be ignored.

参数

无参数

返回

Promise
RemoveResult

示例

// Delete specified document
const result = await db.collection("todos").doc("todo-id-123").remove();

console.log(
"Deleted successfully, number of records impacted:",
result.deleted
);

Operator

Query operator

Get the query operator via db.command to build complex query conditions.

参数

Comparison Operators
object
Logical Operators
object
Field Operators
object
Array Operators
object
Geospatial Operators
object

返回

无参数

示例

const _ = db.command;

Equal to
db.collection("users").where({ age: _.eq(18) });

Not equal to
db.collection("users").where({ status: _.neq("deleted") });

Greater than, greater than or equal to
db.collection("users").where({ age: _.gt(18) });
db.collection("users").where({ age: _.gte(18) });

Less than, less than or equal to
db.collection("users").where({ age: _.lt(60) });
db.collection("users").where({ age: _.lte(60) });

// In the array
db.collection("users").where({ role: _.in(["admin", "editor"]) });

Not in the array
db.collection("users").where({ status: _.nin(["banned", "deleted"]) });

Update operator

Get the update operator via db.command for execution of complex update operations.

参数

Field Operators
object
Array Operators
object

返回

无参数

示例

const _ = db.command;

//Set field value
db.collection("users")
.doc("user-id")
.update({
profile: _.set({ name: "Zhang San", age: 25 }),
});

// Delete field
db.collection("users").doc("user-id").update({
tempData: _.remove(),
});

// Numeric value increment
db.collection("articles")
.doc("article-id")
.update({
viewCount: _.inc(1),
likeCount: _.inc(5),
});

// Numeric value multiplication
db.collection("products")
.doc("product-id")
.update({
price: _.mul(0.9), // 10% off
});

// Get the minimum/maximum value
db.collection("users")
.doc("user-id")
.update({
minScore: _.min(60),
maxScore: _.max(100),
});

// Rename field
db.collection("users")
.doc("user-id")
.update({
oldField: _.rename("newField"),
});

// Bitwise Operation
db.collection("users")
.doc("user-id")
.update({
flags: _.bit({ and: 5 }), // Bitwise AND operation
});

Transaction Operations

Support atomic operations on multiple documents to underwrite data consistency.

Note

-Support only server-side use, not supported on the client.

startTransaction

async db.startTransaction(): Promise<Transaction>

Start a new transaction.

参数

无参数

返回

Promise
Transaction

Transaction object, perform document operations in a transaction

示例

// Start a transaction.
const transaction = await db.startTransaction();

try {
// Operate document in transaction
const doc = transaction.collection("accounts").doc("account-1");
const accountData = await doc.get();

if (accountData.data && accountData.data.balance >= 100) {
// Deducting funds
await doc.update({
balance: accountData.data.balance - 100,
});

// Add balance to another account
await transaction
.collection("accounts")
.doc("account-2")
.update({
balance: db.command.inc(100),
});

// Commit transactions.
await transaction.commit();
console.log("Fund transfer successful");
} else {
// Roll back transaction
await transaction.rollback("INSUFFICIENT_BALANCE");
}
} catch (error) {
// Roll back when an error occurs
await transaction.rollback(error);
console.error("Transaction failure:", error);
}

runTransaction

async db.runTransaction(callback: (transaction) => Promise<any>, times?: number): Promise<void>

Execute transaction operations with automatic processing of submission and rollback.

参数

callback
(transaction) => Promise<void>

Transactional callback function, perform transaction operations in the function

times
number

Retry count for transaction conflicts, defaults to 3

返回

Promise
void

Function return value of the transactional callback function

示例

Use runTransaction to automatically manage transactions
const result = await db.runTransaction(async (transaction) => {
// Obtain account 1
const account1 = await transaction
.collection("accounts")
.doc("account-1")
.get();

Obtains account 2
const account2 = await transaction
.collection("accounts")
.doc("account-2")
.get();

if (account1.data.balance < 100) {
// Roll back via rollback and return custom error
await transaction.rollback({ message: "INSUFFICIENT_BALANCE" });
return;
}

// Deducting funds
await transaction
.collection("accounts")
.doc("account-1")
.update({
balance: account1.data.balance - 100,
});

// Adding funds
await transaction
.collection("accounts")
.doc("account-2")
.update({
balance: account2.data.balance + 100,
});

return { success: true, message: "Fund transfer successful" };
});

console.log(result);

Real-time listening

watch

watch(options: WatchOptions): DBRealtimeListener

Listen to real-time changes in documents or query results.

参数

options
WatchOptions

返回

DBRealtimeListener
object

Listener object

示例

Listen to changes in a single document
const listener = db
.collection("todos")
.doc("todo-id-123")
.watch({
onChange: (snapshot) => {
console.log("document changes:", snapshot);
console.log("document data:", snapshot.docs);
console.log("change details:", snapshot.docChanges);
},
onError: (error) => {
console.error("Listen error:", error);
},
});

// Close listener
// listener.close();

Advanced operation

runCommands

async db.runCommands(params: IRunCommandsReq): Promise<IRunCommandsResult>

Execute MongoDB native commands, support batch operations for multiple commands and transaction operations.

Note

-Only the administrator can call the API -During execution in a transaction, any command failure would cause the entire transaction rollback.

参数

params
IRunCommandsReq

返回

Promise
IRunCommandsResult

示例

// Execute the find command
const result = await db.runCommands({
commands: [
{
find: "users",
filter: { age: { $gte: 18 } },
projection: { name: 1, email: 1 },
sort: { age: -1 },
limit: 10,
},
],
});

console.log("query result:", result.list);
// result.list[0] contains the queried document

Other functions

serverDate

db.serverDate(options?: { offset?: number }): ServerDate

Get server time.

参数

options
object

返回

ServerDate
ServerDate

Server time object

示例

// Use server time
await db.collection("todos").add({
title: "New Task"
createdAt: db.serverDate(), // Current server time
});

// Use server time with offset
await db.collection("todos").add({
title: "Delayed Task"
scheduledAt: db.serverDate({
offset: 60 * 60 * 1000, // 1 hour later
}),
});

RegExp

db.RegExp({ regexp: string, options?: string }): RegExp

Create a regular expression object for fuzzy query.

参数

options
object

返回

RegExp
RegExp

regular expression object

示例

// Fuzzy query: heading contains "CloudBase"
const result = await db
.collection("todos")
.where({
title: db.RegExp({
regexp: "CloudBase",
options: "i", // case-insensitive
}),
})
.get();

console.log("query result:", result.data);

Aggregation Operator

Obtain aggregation operators through db.command.aggregate for expression calculation in the aggregation pipeline.

CategoryOperator
Arithmetic Operatorabs, add, ceil, divide, exp, floor, ln, log, log10, mod, multiply, pow, sqrt, subtract, trunc
Array OperatorarrayElemAt, arrayToObject, concatArrays, filter, in, indexOfArray, isArray, map, range, reduce, reverseArray, size, slice, zip
Boolean Operatorand, not, or
Comparison Operatorcmp, eq, gt, gte, lt, lte, neq
Conditional Operatorcond, ifNull, switch
Date OperatordateFromParts, dateFromString, dayOfMonth, dayOfWeek, dayOfYear, isoDayOfWeek, isoWeek, isoWeekYear, millisecond, minute, month, second, hour, week, year
String Operatorconcat, dateToString, indexOfBytes, indexOfCP, split, strLenBytes, strLenCP, strcasecmp, substr, substrBytes, substrCP, toLower, toUpper
Set OperatorallElementsTrue, anyElementTrue, setDifference, setEquals, setIntersection, setIsSubset, setUnion
Object OperatormergeObjects, objectToArray
Grouping OperatoraddToSet, avg, first, last, max, min, push, stdDevPop, stdDevSamp, sum
Otherliteral, let, meta

-Detailed documentation for aggregate query