Reputation: 97
I have Videos data with title name on each and writing an search api which will get videos data matching title name
exports.findbytitle = (req, res) => {
let userPattern = new RegExp(req.body.title, "i");
Videos.find({ title: userPattern })
.then((video) => {
res.send({ success: true, video });
})
.catch((err) => {
res.send({ success: false, err });
});
};
Problem here is if userPattern
matches I get proper videos, but if userPattern
is empty string example: ("title": ""
) I get all videos instead of error.
What changes should I make to get error if userPattern
is passed as empty string?
Upvotes: 0
Views: 156
Reputation: 20354
Just throw custom error if req.body.title
is not sent or is empty string:
exports.findbytitle = (req, res, next) => {
if(!req.body.title) return res.status(400).json({success:false, message: 'Title is missing.'})
let userPattern = new RegExp(req.body.title, "i");
Videos.find({ title: userPattern })
.then((video) => {
res.send({ success: true, video });
})
.catch((err) => {
res.send({ success: false, err });
});
};
Upvotes: 1
Reputation: 614
As you know only if the title is empty then why aren't you adding a condition before query?
if(!req.body.title) {
return res.send({ success: false, err: new Error("Not found")})
}
Upvotes: 2