You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用strapi.db.query更新数据库时提示‘Update requires a data object’错误

Strapi控制器中通过ID更新数据库条目解决方法

你的代码存在两个核心问题,导致出现Error: Update requires a data object.报错:

  1. update方法参数格式错误:Strapi v4的db.query().update()仅接受一个配置对象,不需要将ID作为独立的第一个参数传入。
  2. where条件写法错误:{ otpSent }会被解析为{ otpSent: otpSent },这不是按ID匹配数据的正确条件。

正确写法示例

方法1:使用db.query更新

确保参数是包含where和data的单一对象,同时明确用ID作为匹配条件:

try {
  await strapi.db.query("api::otp.otp").update({
    where: { id: otpSent.id },
    data: data, // 必须是包含更新字段的非空对象,比如{ verified: true }
  });
} catch (error) {
  console.log(error);
}

方法2:使用Strapi Entity Service(更简洁)

Entity Service的update方法支持直接传入ID作为第一个参数,更符合你最初的写法逻辑:

try {
  await strapi.service("api::otp.otp").update(otpSent.id, {
    data: data,
  });
} catch (error) {
  console.log(error);
}

关键注意事项

  • 必须确保data变量是非空的有效对象,不能是undefined或null,比如要更新验证码状态,需传入{ verified: true, expiresAt: new Date() }这类明确的键值对结构。
  • 如果otpSent是从数据库查询得到的实体,直接使用其id字段即可完成精准匹配,无需额外的复杂条件。

内容的提问来源于stack exchange,提问作者Wai Yan Kyaw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 23:06:32