Skip to main content

CRUD

Initialize the SDK

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

const app = cloudbase.init({
env: "your-env-id", // Replace with your environment id
});

const db = app.database();
const _ = db.command; // Obtain the query command

Adding Data

Insert Single Record

Insert a new record into the collection.

Parameter Description

ParameterTypeRequiredDescription
dataobjectRequiredData object to be added

Code Example

// Insert a single record
const result = await db.collection('todos').add({
title: 'Learn CloudBase',
content: 'Complete the database operations tutorial',
completed: false,
priority: 'high',
createdAt: new Date(),
tags: ['Learning', 'Technology']
})

console.log('Added successfully, Document ID:', result._id)

Adding Geographic Locations

// Create a geographic location point
const point = new db.Geo.Point(longitude, latitude);

// Create a geographic path
const line = new db.Geo.LineString([
new db.Geo.Point(lngA, latA),
new db.Geo.Point(lngB, latB)
]);

// Create a geographic area
const polygon = new db.Geo.Polygon([
new db.Geo.LineString([
new db.Geo.Point(lngA, latA),
new db.Geo.Point(lngB, latB),
new db.Geo.Point(lngC, latC),
new db.Geo.Point(lngA, latA) // closed
])
]);

const result = await db.collection('todos').add({
location: point,
path: line,
area: polygon
})

Querying Data

Query Single Record

Query the specified record via document ID.

Parameter Description

ParameterTypeRequiredDescription
docIdstringRequiredUnique identifier for the document

Code Example

// Query a single record via document ID
const result = await db.collection('todos')
.doc('docId')
.get()

Returned Results

{
data: [{
_id: "todo-id-123",
title: "Learn CloudBase",
completed: false,
// ... other fields
}],
}

Query Multiple Records

Query multiple records in a collection, supporting conditional filtering, sorting, pagination, and more.

⚠️ Note: The get() method returns 100 records by default. If you need more data, please use pagination.

Parameter Description

MethodParameter TypeRequiredDescription
where()objectNoQuery condition that supports operators
orderBy()string, stringNoSort field and direction ('asc' or 'desc')
limit()numberNoMaximum number of records to return (default: 100, max: 1000)
skip()numberNoNumber of records to skip for pagination
field()objectNoSpecifies the fields to return (true: return, false: exclude)
// Query all records
const result = await db.collection('todos').get()

// Conditional query
const result = await db.collection('todos')
.where({
completed: false,
priority: 'high'
})
.get()

Complex Queries

const _ = db.command

// Complex conditional query
const result = await db.collection('todos')
.where({
// Age is greater than 18
age: _.gt(18),
// tag contains 'technology'
tags: _.in(['Technology', 'Learning']),
// Creation time is within the last week
createdAt: _.gte(new Date(Date.now() - 7 * 24 * 60 * 60 * 1000))
})
.orderBy('createdAt', 'desc') // Sort by creation time in descending order
.limit(10) // Limit to 10 records
.skip(0) // Skip 0 records (pagination)
.field({ // Return only specified fields
title: true,
completed: true,
createdAt: true
})
.get()

Pagination Query

// Pagination Query Example
const pageSize = 10
const pageNum = 1

const result = await db.collection('todos')
.orderBy('createdAt', 'desc')
.skip((pageNum - 1) * pageSize)
.limit(pageSize)
.get()

Aggregate Query

// Statistical Query
const result = await db.collection('todos')
.aggregate()
.group({
_id: '$priority',
count: {
$sum: 1
}
})
.end()

console.log('Statistics by priority:', result.list)

Geographic Location Query

⚠️ Note: When querying geographic location fields, please create a geographic location index; otherwise, the query will fail.

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

// Query users within a specified area
db.collection("users").where({
location: _.geoWithin({
geometry: polygon // Use the polygon defined above
})
}).get()

// Query users intersecting with the path
db.collection("users").where({
location: _.geoIntersects({
geometry: line // Use the line defined above
})
}).get()

Update Data

Update a Single Record

Update the specified record via document ID.

Parameter Description

ParameterTypeRequiredDescription
docIdstringRequiredDocument ID to update
dataobjectRequiredData object to update

Code Example

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

Batch Update

Batch update multiple records based on query conditions.

Parameter Description

ParameterTypeRequiredDescription
whereobjectRequiredQuery condition that specifies the records to update
dataobjectRequiredData object to update

Code Example

// Batch update multiple records.
const batchResult = await db.collection('todos')
.where({
completed: false,
priority: 'low'
})
.update({
priority: 'normal',
updatedAt: new Date()
})

Update or Create

Update the document, or create it if it does not exist:

const setResult = await db.collection('todos')
.doc("doc-id")
.set({
completed: false,
priority: 'low'
})

Delete Data

Single Record Deletion

Delete the specified record via document ID.

Parameter Description

ParameterTypeRequiredDescription
docIdstringRequiredDocument ID to delete

Code Example

// Delete the specified document
const result = await db.collection('todos')
.doc('todo-id')
.remove()

Batch Deletion

Batch delete multiple records based on query conditions.

Parameter Description

ParameterTypeRequiredDescription
whereobjectRequiredQuery condition that specifies the records to delete

Code Example

// Batch delete multiple records
const _ = db.command
const batchResult = await db.collection('todos')
.where({
completed: true,
createdAt: _.lt(new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)) // 30 days ago
})
.remove()

Supported Document Operations

MethodDescriptionExample
add()Add a documentdoc.add(data)
get()Query a documentdoc.get()
update()Update a documentdoc.update(data)
set()Set a document (create if not exists)doc.set(data)
remove()Delete a documentdoc.remove()
count()Count documentsdoc.count()
where()Query conditionsdoc.where(condition)
orderBy()Sort documentsdoc.orderBy(field, order)
limit()Limit the numberdoc.limit(num)
skip()Skip the numberdoc.skip(num)
field()Specify fieldsdoc.field(fields)
doc()Get a document referencedoc.doc(id)
watch()Real-time listeningdoc.watch(options)