Reputation: 882
I wanted to know if with mongoose (node.js) I can search for a value in two parameters. For example, let's say that I have a string and I want to look in the user's collection for a user who has either the same email as the string or the username that is the same. Those first mongoose will search for the value in a field and if it does not complete the search successfully it will search for the same value but in the second field (in this case the email). Thanks to everyone in advance
Upvotes: 0
Views: 613
Reputation: 909
You could try the code below to search a User model using either username or email. The return a 404 status is user not found, 500 if it encounters an error and the default 200 on success with the user object.
User.findOne({
$or: [
{username: req.body.fieldName},
{email: req.body.fieldName}
]
}).then((user)=>{
if(user==null) return res.status(404).json({
success: false,
message: 'No user found'
})
return res.json({
success: true,
user: user
})
}).catch((err)=>{
return res.status(500).json({
success: false,
message: 'Encountered an error finding user',
error: err
})
})
Upvotes: 3