码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2016-10-11 18:27:23      阅读:631      评论:0      收藏:0      [点我收藏+]

标签:

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

比如我们这个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~~

 

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

标签:

原文地址:http://www.cnblogs.com/heziyu/p/5950011.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!