简体   繁体   中英

How to return conditional response on MongoDB findOne?

I have a check to see if the email entered or the username entered exists in the database to prevent duplicates from being created. It successfully checks if it is the email or the username that exists but I do not know how to return which exists in the error response. Currently it just returns that both of them exist even if hypothetically it was only the email that exists and not the username.

User.findOne({$or: [{email: req.body.email}, {name: req.body.name}]}).then(user => {
 if (user) {
     return res.status(400).json({ name: "Username exists", email: "Email exists" });
 } 
});

Extract your response into an object

 return res.status(400).json(response_obj)

and build it conditionally

response_obj = {}
if (user.email) {
  response_obj.email = "Email exists."
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM