今天在對接接口的時候遇到一些問題,因為之前為了方便驗證接口寫的對不對是往數據庫里面自己插的一些數據,剛開始用的時候還用的不亦樂乎,后來遇到更新的時候出錯了。
比如我們這個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~~