Fetch Data
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.rdb();
Basic Queries
Query table data through the select() method, supporting features such as conditional filtering and join queries.
db.from(tableName).select(columns, options)
- tableName: table name
- columns: columns to retrieve, separated by commas
- options: query options configuration
Parameter Description
| Parameter | Type | Required | Description |
|---|---|---|---|
| columns | string | No | Columns to retrieve, separated by commas. Supports using aliasName:foreignKey(columns) syntax to rename foreign key related fieldscolumns takes * to query all fields |
| options | object | No | Query options configuration |
options Parameter Description
| Parameter | Type | Required | Description |
|---|---|---|---|
| count | string | No | Counting algorithm, optional values: "exact" - underlying execution of COUNT(*) |
| head | boolean | No | When set to true, no data is returned. This is only useful for counting |
Code Examples
Query All Data
// Query all data from the articles table
const { data, error } = await db.from("articles").select();
console.log('Query result:', data);
Query Specific Columns
// Only query article titles and creation times
const { data, error } = await db.from("articles").select("id, title, created_at");
console.log('Query result:', data);
Query Foreign Key Related Data
// Use alias 'category' instead of the default 'categories' field name
const { data, error } = await db.from("articles").select(`
id,
title,
created_at,
category:categories(name)
`);
console.log('Query result:', data);
Return Result
{
data: [
{
id: 1,
title: "Article Title",
created_at: "2023-01-01T00:00:00Z",
category: {
name: "Frontend Development"
}
},
// ... other records
],
error: null
}
Join Table Queries
Join queries allow you to retrieve data from multiple tables simultaneously, supporting one-to-one, one-to-many, and other relationships.
Example Table Structure
To better understand join queries, let's first look at the table structure used in the examples:
Table Relationship Description:
- The
articlestable has a many-to-one relationship with thecategoriestable throughcategory_id - The
articlestable has a many-to-one relationship with theuserstable throughcreated_by(creator) - The
articlestable has a many-to-one relationship with theuserstable throughupdated_by(updater)
View the complete SQL CREATE TABLE statements
-- Users table
CREATE TABLE users (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100)
);
-- Categories table
CREATE TABLE categories (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100)
);
-- Articles table
CREATE TABLE articles (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(256),
content TEXT,
category_id BIGINT,
created_by BIGINT,
updated_by BIGINT,
created_at TIMESTAMP,
updated_at TIMESTAMP,
FOREIGN KEY (category_id) REFERENCES categories(id),
CONSTRAINT articles_created_by_fkey FOREIGN KEY (created_by) REFERENCES users(id),
CONSTRAINT articles_updated_by_fkey FOREIGN KEY (updated_by) REFERENCES users(id)
);
Basic Join Query
// Query article data while fetching associated category information
// Based on the articles.category_id = categories.id relationship
const { data, error } = await db.from("articles").select(`
title,
categories(name)
`);
console.log('Query result:', data);
View return result example
[
{
title: "JavaScript Beginner Tutorial",
categories: {
name: "Frontend Development"
}
},
{
title: "Node.js in Practice",
categories: {
name: "Backend Development"
}
}
]
Multiple Join Query
// Query articles while fetching creator and updater information
// Use aliases to distinguish different user relationships, making the returned data more readable
const { data, error } = await db.from("articles").select(`
title,
creator:users!articles_created_by_fkey(name),
updater:users!articles_updated_by_fkey(name)
`);
console.log('Query result:', data);
View return result example
[
{
title: "JavaScript Beginner Tutorial",
creator: { // Using alias 'creator' for the creator
name: "Zhang San"
},
updater: { // Using alias 'updater' for the updater
name: "Li Si"
}
}
]
Note: When the same table is associated multiple times through different foreign keys, you must use the foreign key constraint name (e.g.,
!articles_created_by_fkey) to distinguish different relationships. It is recommended to use alias syntax to make the returned data fields more semantic.
Nested Join Query
// Query categories with all their articles, and the author information for each article
// This is a three-level nested join query: categories -> articles -> users
const { data, error } = await db.from("categories").select(`
name,
articles (
title,
users (
name
)
)
`);
console.log('Query result:', data);
View return result example
[
{
name: "Frontend Development",
articles: [
{
title: "JavaScript Beginner Tutorial",
users: {
name: "Zhang San"
}
},
{
title: "Vue.js in Practice",
users: {
name: "Li Si"
}
}
]
},
{
name: "Backend Development",
articles: [
{
title: "Node.js in Practice",
users: {
name: "Wang Wu"
}
}
]
}
]
Advanced Queries
Conditional Filtering Query
// Query all articles under a specific category
// Filter by category name to get all articles in that category
const { data, error } = await db
.from("articles")
.select("title, categories(*)")
.eq("categories.name", "Tech Articles");
console.log('Query result:', data);
View return result example
[
{
title: "JavaScript Advanced Features",
categories: {
id: 1,
name: "Tech Articles"
}
},
{
title: "Database Optimization Tips",
categories: {
id: 1,
name: "Tech Articles"
}
}
]
Count Query
// Get each category and its article count
// count will calculate how many articles are in each category
const { data, error } = await db
.from("categories")
.select(`*, articles(count)`);
console.log('Query result:', data);
View return result example
[
{
id: 1,
name: "Frontend Development",
articles: [
{ count: 5 } // 5 articles in this category
]
},
{
id: 2,
name: "Backend Development",
articles: [
{ count: 3 } // 3 articles in this category
]
}
]
Get Count Only
// Only get the total article count without returning actual data
const { count, error } = await db
.from("articles")
.select("*", { count: "exact", head: true });
console.log('Total count:', count);
Inner Join Query
// Only get articles that have a category, using inner join to ensure the category exists
// !inner ensures that only articles with matching records in the categories table are returned
const { data, error } = await db
.from("articles")
.select("title, categories!inner(name)")
.eq("categories.name", "Tutorial")
.limit(10);
console.log('Query result:', data);
View return result example
[
{
title: "JavaScript Basic Tutorial",
categories: {
name: "Tutorial"
}
},
{
title: "React Beginner Tutorial",
categories: {
name: "Tutorial"
}
}
]
Note:
!innerindicates an inner join, which only returns data that has matching records in the related table. Without!inner, even if an article'scategory_idis null or points to a non-existent category, the article will still be returned with a nullcategoriesfield.