I am querying Mongoose db with a search, where the title is the "customTitle" from the URL.
The search works well if I search for all items, e.g.
Article.find(err, foundArticles) =>
, but I am getting an empty query response to Article.find({title:/customTitle/i}, (err, foundArticles) => {
I'd like to get a response with all items, that contains "customTitle" variable in any record.
app.route("/:customTitle")
.get(function(req, res){
const customTitle = _.capitalize(req.params.customTitle);
Article.find({title:/customTitle/i}, (err, foundArticles) => {
if (!err){
res.send(foundArticles);
console.log(typeof customTitle " ", customTitle);
console.log(foundArticles);
} else {
res.send(err);
}
});
What is the problem here, please? Thank you.
CodePudding user response:
You need to create the regex using new RegExp
. You are searching for the literal string customTitle
.
For example:
const rx = new RegExp(customTitle, 'i')
query.find({title:rx})
CodePudding user response:
I've found, that I can use RegExp of Mongoose and JavaScript
Mongoose RegExp that works:
app.route("/:customTitle")
.get(function(req, res) {
const customTitle = _.capitalize(req.params.customTitle);
Article.find({ title: {$regex: customTitle, $options:'i'}}, (err, foundArticles) => {
if (!err) {
res.send(foundArticles);
} else {
res.send(err);
}
});
And JavaScript RegExp that works:
app.route("/:customTitle")
.get(function(req, res) {
const customTitle = _.capitalize(req.params.customTitle);
const rx = new RegExp(customTitle, 'i');
Article.find({title:rx}, (err, foundArticles) => {
if (!err) {
res.send(foundArticles);
} else {
res.send(err);
}
});