Node+Express+Mongoose栈MongoDB数组字段POST/PATCH均为空问题求助
问题根源
你的问题由字段名拼写不一致导致,Mongoose 默认会静默忽略 Schema 中未定义的字段,因此你传入的数组值没有被正确写入数据库,最终返回空数组。
具体差异:
- Schema 中定义的数组字段名为
taskIds - POST、PATCH 接口的赋值逻辑中错误写为多了一个 s 的
tasksIds
修复方案
- 修正创建接口的字段拼写
修改/create接口的模型初始化代码:
const column = new columnModel({ title: req.body.title, taskIds: req.body.taskIds, // 把tasksIds改为taskIds });
- 修正更新接口的字段拼写
修改/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
相关产品推荐
相关产品推荐

