更新数据
初始化 SDK
import cloudbase from "@cloudbase/js-sdk";
const app = cloudbase.init({
env: "your-env-id", // 替换为您的环境id
});
const models = app.models;
单条更新
根据条件更新单条记录。
models.modelName.update(options);
- modelName: 数据模型名称
- options: 更新参数
options 参数说明
具体查询参数说明请参考 查询参数详解 文档。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| data | object | 是 | 要更新的数据对象 |
| filter.where | object | 是 | 查询条件,确定要更新的记录 |
代码示例
// 更新单条记录
const result = await models.todo.update({
data: {
title: "更新后的任务",
completed: true,
updatedAt: new Date(),
updatedBy: "admin",
},
filter: {
where: {
_id: {
$eq: "todo-id", // 推荐使用 _id 进行精确操作
},
},
},
});
console.log("更新结果:", result);
批量更新
根据查询条件批量更新多条记录。
⚠️ 注意:暂不支持批量更新关联关系字段
models.modelName.updateMany(options);
- modelName: 数据模型名称
- options: 更新参数
options 参数说明
具体查询参数说明请参考 查询参数详解 文档。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| data | object | 是 | 要更新的数据对象 |
| filter.where | object | 是 | 查询条件,确定要更新的记录 |
代码示例
// 批量更新多条记录
const result = await models.todo.updateMany({
data: {
status: "archived",
archivedAt: new Date(),
},
filter: {
where: {
completed: {
$eq: true,
},
createdAt: {
$lt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), // 30天前
},
},
},
});
console.log("批量更新结果:", result);
创建或更新数据
根据查询条件创建或更新记录。
⚠️ 注意:暂不支持批量新增更新关联关系字段
models.modelName.upsert(options);
- modelName: 数据模型名称
- options: 更新参数
options 参数说明
具体查询参数说明请参考 查询参数详解 文档。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| create | object | 是 | 要新增的数据对象 |
| update | object | 是 | 要更新的数据对象 |
| filter.where | object | 是 | 查询条件,确定要更新的记录 |
代码示例
const post = {
title: "Hello World",
body: "Hello World",
_id: "foo",
};
const { data } = await models.post.upsert({
create: post,
update: post,
filter: {
where: {
_id: {
$eq: post._id,
},
},
},
});
console.log(data);