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

Next.js博客开发中如何将Editor.js数据存储到MongoDB

报错原因

你在Mongoose Schema中定义post字段的类型为String,但Editor.js调用save()方法返回的是包含time、blocks、version属性的原生JavaScript对象,你直接将该对象赋值给post字段传入数据库,Mongoose在类型校验时无法将对象转换为字符串,因此抛出类型转换失败的报错。

解决方法

提供两种可选方案:

方案1:序列化对象为字符串存储(更通用,无需修改表结构)

在提交数据时,将Editor.js返回的post对象序列化为JSON字符串,读取时再反序列化为对象即可。
修改提交逻辑的blog构造部分:

const blog = {
  title,
  description,
  images,
  post: JSON.stringify(post), // 序列化对象为字符串
};

后续从数据库查询到数据渲染Editor.js时,将字符串转回对象:

// 假设从接口拿到的博客数据为res.data
setPost1(JSON.parse(res.data.post))

方案2:修改Mongoose Schema适配对象类型

直接调整Schema中post字段的类型,允许存储对象,不需要额外做序列化/反序列化操作:

// 方案2.1 用Mixed类型适配任意结构的对象
post: {
  type: mongoose.Schema.Types.Mixed,
  // required: true,
}

// 方案2.2 更严谨的固定结构定义,匹配Editor.js的输出格式
post: {
  time: { type: Number, required: true },
  blocks: { type: Array, required: true },
  version: { type: String, required: true }
}

修改Schema后原有的提交逻辑不需要改动,直接传post对象即可正常存储。

内容的提问来源于stack exchange,提问作者Kennedy Daniel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:36:04