models/userModel.js
const userSchema = mongoose.Schema(
{
name: {
type: String,
required: true,
},
username: {
type: String,
required: true,
unique: true,
},
},
)
controllers/userController.js
export const findUserConversation = async(req, res) => {
const { name } = req.params
try{
let user
user = await User.find({$or: [
{ name: { $regex: name, $options: 'i'} },
{ username: { $regex: name, $options: 'i'} }
]}).select("-password").select("-updatedAt")
console.log(user)
if(!user){
return res.status(404).json({ error: "User not found" })
}
res.status(200).json(user)
} catch(error){
res.status(500).json({ error: error.message });
console.log("Error in getUserProfile: ", error.message);
}
}
I have a problem that I would like to write a controller that would return the result when part of the query param value exists on the User model either name or username and I tried to type a string that not exists in the model the error message could not be read instead returning an empty array only. I am wondering what is the best way to return the result from the database if part of the string exists in specific fields
I searched and searched but could not find out the best solution to fix the issue.
MERN is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.