跳到主要内容

更新数据

初始化 SDK

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

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

const models = app.models

单条更新

根据条件更新单条记录。

参数说明

参数类型必填说明
dataobject要更新的数据对象
filter.whereobject查询条件,确定要更新的记录

代码示例

// 更新单条记录
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)

批量更新

根据查询条件批量更新多条记录。

暂不支持批量更新关联关系字段

参数说明

参数类型必填说明
dataobject要更新的数据对象
filter.whereobject查询条件,确定要更新的记录

代码示例

// 批量更新多条记录
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)

创建或更新数据

根据查询条件创建或更新记录。

暂不支持批量新增更新关联关系字段

参数说明

参数类型必填说明
createobject要新增的数据对象
updateobject要更新的数据对象
filter.whereobject查询条件,确定要更新的记录
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);