跳到主要内容

增删改查

🔧 SDK 初始化

请参考 SDK 初始化 文档进行初始化配置。初始化后拿到对应的模型实例 models ,即可开始进行数据操作。

🔍 查询数据

单条查询

通过指定条件查询单条记录。

参数说明

参数类型必填说明
filter.whereobject❌ 否查询条件
selectobject❌ 否指定返回字段

代码示例

// 根据 ID 查询单条记录
const todo = await models.todo.get({
filter: {
where: {
_id: {
$eq: "todo-id-123"
}
}
}
})

console.log('查询结果:', todo.records[0])

返回结果

{
records: [{
_id: "todo-id-123",
title: "服务端任务",
completed: false,
// ... 其他字段
}],
total: 1
}

多条查询

查询多条记录,支持条件筛选、排序、分页等。具体参数说明请参考 数据模型查询操作 文档。

代码示例

// 基础查询
const todos = await models.todo.list({
filter: {
where: {
completed: {
$eq: false
}
},
orderBy: [{
field: "priority",
direction: "desc"
},
{
field: "createdAt",
direction: "asc"
}
],
limit: 100
}
})

console.log('查询结果:', todos.records)

返回结果

{
records: [{
_id: "todo-id-1",
title: "任务1",
completed: false
},
{
_id: "todo-id-2",
title: "任务2",
completed: true
}
],
total: 2
}

➕ 新增数据

单条新增

向数据模型中添加一条新记录。

参数说明

参数类型必填说明
dataobject✅ 是要新增的数据对象

代码示例

// 创建单条记录
const todo = await models.todo.create({
data: {
title: "服务端任务",
description: "使用 node-sdk 创建的任务",
priority: "high",
completed: false,
createdAt: new Date(),
createdBy: "system",
metadata: {
source: "api",
version: "1.0"
}
}
})

console.log('创建成功:', todo)

批量新增

一次性向数据模型中添加多条记录。

参数说明

参数类型必填说明
dataarray✅ 是包含多个数据对象的数组

代码示例

// 批量创建多条记录
const todos = await models.todo.createMany({
data: [{
title: "批量任务1",
priority: "high"
},
{
title: "批量任务2",
priority: "medium"
},
{
title: "批量任务3",
priority: "low"
}
]
})

console.log('批量创建成功:', todos)

📝 更新数据

单条更新

根据条件更新单条记录。

参数说明

参数类型必填说明
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)

🗑️ 删除数据

单条删除

根据条件删除单条记录。

参数说明

参数类型必填说明
filter.whereobject✅ 是查询条件,确定要删除的记录

代码示例

// 删除单条记录
const result = await models.todo.delete({
filter: {
where: {
_id: {
$eq: "todo-id"
}
}
}
})

console.log('删除结果:', result)

批量删除

根据查询条件批量删除多条记录。

参数说明

参数类型必填说明
filter.whereobject✅ 是查询条件,确定要删除的记录

代码示例

// 批量删除已完成的任务
const result = await models.todo.deleteMany({
filter: {
where: {
completed: {
$eq: true
},
createdAt: {
$lt: new Date(Date.now() - 90 * 24 * 60 * 60 * 1000) // 90天前
}
}
}
})

console.log('批量删除结果:', result)