如何使用Mongoose和Node.js更新MongoDB中的用户设备列表字段
问题修复方案
现有代码的问题
- 数据结构不匹配:你定义的
devices是{device: ObjectId}格式的对象数组,现有代码直接把device值塞进去,格式不符合schema要求 - 异步操作未加await:
updatedUser.save()是异步方法,未加await会导致保存操作还没完成就提前返回响应,数据不会持久化到数据库 - 缺少边界判断:没有校验查询到的用户是否存在,也没有校验入参是否合法
- 存在语法错误:代码末尾有多余的闭合括号
});,会直接触发运行报错 - 其他字段更新逻辑缺失:原代码只写了
name字段的更新逻辑,lastname、email等其他字段的更新逻辑缺失
修改后的完整代码
const updateUser = async (req, res, next) => { const { name, lastname, email, password, userTyp, device } = req.body; const userID = req.params.userID; let updatedUser; try { updatedUser = await User.findById(userID); // 校验用户是否存在 if (!updatedUser) { return next(new HttpError('对应用户不存在', 404)); } } catch(err) { console.log(err); return next(new HttpError('查询用户信息出错', 500)); } // 基础字段增量更新,不存在的字段保留原值 if (name) updatedUser.name = name; if (lastname) updatedUser.lastname = lastname; if (email) updatedUser.email = email; if (password) updatedUser.password = password; if (userTyp) updatedUser.userTyp = userTyp; // 按schema要求的结构追加设备,device存在才执行追加 if (device) { updatedUser.devices.push({ device: device }); } try { // 加await等待数据库保存完成 await updatedUser.save(); } catch (err) { console.log(err); return next(new HttpError('更新用户信息失败', 500)); } res.status(200).json({user: updatedUser.toObject( {getters: true} )}); };
可选优化(避免重复添加同一个设备)
如果需要避免同一个设备ID重复加入用户设备列表,可以把追加设备的逻辑替换为:
if (device) { const isDeviceExist = updatedUser.devices.some(item => item.device.toString() === device.toString()); if (!isDeviceExist) { updatedUser.devices.push({ device: device }); } }
内容的提问来源于stack exchange,提问作者Eliotkuri
相关产品推荐
相关产品推荐

