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

Node+Express+Mongoose栈MongoDB数组字段POST/PATCH均为空问题求助

问题根源

你的问题由字段名拼写不一致导致,Mongoose 默认会静默忽略 Schema 中未定义的字段,因此你传入的数组值没有被正确写入数据库,最终返回空数组。
具体差异:

  • Schema 中定义的数组字段名为 taskIds
  • POST、PATCH 接口的赋值逻辑中错误写为多了一个 s 的 tasksIds

修复方案

  1. 修正创建接口的字段拼写
    修改 /create 接口的模型初始化代码:
const column = new columnModel({
  title: req.body.title,
  taskIds: req.body.taskIds, // 把tasksIds改为taskIds
});
  1. 修正更新接口的字段拼写
    修改 /update/:id 接口的更新参数,同时新增配置返回更新后的最新文档:
const updatedColumn = await columnModel.findByIdAndUpdate(id, {
  title: req.body.title,
  taskIds: req.body.taskIds, // 把tasksIds改为taskIds
}, { new: true }); 

可选优化配置

如果希望后续排查类似拼写错误更简单,可以在 Schema 定义中开启严格模式抛错配置,遇到未定义字段赋值时直接抛出错误,避免静默失败:

const ColumnSchema = new mongoose.Schema({
  title: { type: String, required: true },
  taskIds: { type: [String], required: true },
}, { strict: 'throw' });

内容的提问来源于stack exchange,提问作者Mac Bubb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 09:18:04