REST API调用未传参时如何避免将Mongoose对象属性覆盖为null
解决方案
你可以通过动态过滤更新字段的方式实现需求,不需要手写大量if判断,常用实现方式如下:
方式1:原生JS实现(无额外依赖)
直接过滤请求体中未传递的undefined字段,仅保留客户端实际传入的参数用于更新:
router.put('/:id', async (req, res) => { // 过滤出请求中实际传递的非undefined字段 const updateFields = Object.fromEntries( Object.entries(req.body).filter(([_, value]) => value !== undefined) ); // 对date字段做单独的类型转换 if (updateFields.date) { updateFields.date = new Date(updateFields.date); } // 建议新增runValidators参数,保证更新时触发Schema定义的字段校验规则 const reservation = await Reservation.findByIdAndUpdate( req.params.id, updateFields, { new: true, runValidators: true } ); res.send(reservation); });
方式2:借助lodash简化(项目已引入lodash时推荐)
用lodash的pickBy方法快速过滤空字段,代码更简洁:
const _ = require('lodash'); router.put('/:id', async (req, res) => { // 过滤掉请求体中的undefined、null等值 const updateFields = _.pickBy(req.body, _.identity); if (updateFields.date) updateFields.date = new Date(updateFields.date); const reservation = await Reservation.findByIdAndUpdate( req.params.id, updateFields, { new: true, runValidators: true } ); res.send(reservation); });
注意事项
- 如果你的业务逻辑允许客户端主动把字段设置为
null,只需调整过滤条件,保留value === null的情况即可 - 新增的
runValidators参数会触发Schema中定义的长度、必填等校验规则,避免非法数据入库,建议加上
内容的提问来源于stack exchange,提问作者Mickey
相关产品推荐
相关产品推荐

