[英]I want to check another field When I get dublicate key error for email (unique) in mongodb findoneandupdate
[英]When I get dublicate key error for email (unique) , I want to check another field in mongodb findoneandupdate
我正在使用mongodb和nodejs。 我想更新用戶,如果電子郵件發生了公開密鑰錯誤(唯一),則檢查isdelete(非唯一)字段。如果isdelete等於true,否則更新用戶。
//user is a model
User.findOne({ 'email': req.body.email, 'isDeleted': true}, function (err, result) {
if(result) { //if user isdeleted true then update user
//write here your update code
}
});
User.findOneAndUpdate({ _id: userFindByid }, {
$set: {
"email": req.body.email,
"username": req.body.username,
"phone_number": req.body.phone_number,
"address": req.body.address,
"isBenefactor": req.body.isBenefactor,
"location": req.body.location
}
}, { runValidators: true, context: 'query' }, (err, doc) => {
if (err) {
// if request email has already exist in db I want to check that emails isDeleted field in here . if isDeleted is true I want to update .
return res.status(500).json({ message: err.message });
}
else {
return res.status(200).json({ message: 'Your account was updated' });
}
})
//
Let me explain scenario clearly,
I registered with an email address(first@gmail.com) then I deleted my account =>(first@gmail.com)=>isDeleted=true
After that I again registered with another email address(second@gmail.com)=>isDeleted=false
Now I want to update my second email address with first one I will get an unique key error because (first@gmail.com) is in mydb ,but I have to da update process because (first@gmail.com)=>IsDelete=true
If I use { 'email': req.body.email, 'isDeleted': true} I can not update (second@gmail.com)=>isDeleted=false
I can fix the problem by using too much if statements , but I dont want to use if statements too much. I am looking for best practice for that problem.
I hope I could explain
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.