mongodb 数据更新与_id之间的故事

今天在对接接口的时候遇到一些问题,因为之前为了方便验证接口写的对不对是往数据库里面自己插的一些数据,刚开始用的时候还用的不亦乐乎,后来遇到更新的时候出错了。

比如我们这个APP是个医疗APP刚开始注册的时候默认都为病人,如下

 

当有医生想要在这个APP注册赚钱的时候需要注册提交自己的信息,如下

然后按道理来说会注册成功但是却报After applying the update to the document {_id: 3 , ...}, the (immutable) field \'_id\' was found to have been altered to _id: 17' }

我当时也不知道到底是什么出了问题后来问了和我一起刚来的同事(也是菜鸟)说是数据库里面最开始是手动插入的数据,然后更新的时候_id 重复冲突了,当时听了删了很多数据,最后确实是可以,可是我虽然是菜鸟我觉得这个不是问题的本质。

接着我不停的查资料后来才知道问题本质是我代码写的有问题如下:

//医生认证
router.post('/doctorAuth',function (req,res) {
console.log('请求对象:',req.body);
User.update(
{
_id: req.body.doctor_id,
nickname: req.body.nickname,
hospital: req.body.hospital,
address: req.body.address,
license: req.body.license,
photo: req.body.photo,
identity:enums.identityPerson.doctor,
state: enums.authState.pass,
department: req.body.department,
speciality: req.body.speciality
},function (err,doctorAuth) {
if(err) throw err;
if (doctorAuth.nModified == 0 && doctorAuth.n == 0) {
res.send(errors.e112);
return;
}
console.log(doctorAuth);
res.send(errors.e0);
})
里面我update把_id带上了,要知道mongodb中的_id是不可以更新的。终于找到问题所在,然后简单修改代码如下:

//医生认证
router.post('/doctorAuth',function (req,res) {
console.log('请求对象:',req.body);
User.update(
{
_id: req.body.doctor_id
},
{
nickname: req.body.nickname,
hospital: req.body.hospital,
address: req.body.address,
license: req.body.license,
photo: req.body.photo,
identity:enums.identityPerson.doctor,
state: enums.authState.pass,
department: req.body.department,
speciality: req.body.speciality
},function (err,doctorAuth) {
if(err) throw err;
if (doctorAuth.nModified == 0 && doctorAuth.n == 0) {
res.send(errors.e112);
return;
}
console.log(doctorAuth);
res.send(errors.e0);
})

});
然后就可以了。吃了一大亏找到了教训,以后再也不会犯这种问题了。可能在你们面前这个都不是问题,可对于我这个菜鸟来说解决了就感觉非常开心O(∩_∩)O~~

 

转载于:https://www.cnblogs.com/heziyu/p/5950011.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值