查询数据
初始化 SDK
import cloudbase from "@cloudbase/js-sdk";
const app = cloudbase.init({
env: "your-env-id",
});
const models = app.models
单条查询
通过指定条件查询单条记录。
参数说明
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
filter.where | object | 否 | 查询条件 |
select | object | 是 | 指定返回字段 |
代码示例
// 根据 ID 查询单条记录
const todo = await models.todo.get({
filter: {
where: {
_id: {
$eq: "todo-id-123"
}
}
}
})
console.log('查询结果:', todo.data)
返回结果
{
data: {
records: [{
_id: "todo-id-123",
title: "服务端任务",
completed: false,
// ... 其他字段
}],
total: 1
}
}
多条查询
查询多条记录,支持条件筛选、排序、分页等。具体参数说明请参考 查询参数详解 文档。
参数说明
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
filter.where | object | 否 | 查询条件 |
select | object | 是 | 指定返回字段 |
代码示例
// 基础查询
const todos = await models.todo.list({
filter: {
where: {
completed: {
$eq: false
}
},
orderBy: [{
field: "priority",
direction: "desc"
},
{
field: "createdAt",
direction: "asc"
}
]
}
})
console.log('查询结果:', todos.data)
返回结果
{
data: {
records: [{
_id: "todo-id-1",
title: "任务1",
completed: false
},
{
_id: "todo-id-2",
title: "任务2",
completed: true
}
],
total: 2
}
}