I have a document like:
{
id: string,
blogCover:{ title: string },
published: boolean
}
I am using $regex to create a search system as follows:
app.post('/searchblogs',(req,res)=>{
var searchfield = req.body.query;
TFBlog.find({"blogCover.title":{
$regex:searchfield,
$options:'$i'
}}).then((docs)=>{
res.send(docs);
});
});
Now I want search results to only include documents with published:true
I used $match like
TFBlog.find({"blogCover.title":{
$match : { published : true },
$regex:searchfield,
$options:'$i'
}}).then((docs)=>{
res.send(docs);
});
This gives an error :
(node:16304) UnhandledPromiseRejectionWarning: Error: Can't use $match with String.
What should I do ? is there any alternative to achieve this???
$match is a stage in aggregate() query, and it can not be used in find(). Change your code like this:
TFBlog.find({
"blogCover.title": { $regex: searchfield, $options: 'i' },
"published": true
}).then((docs) => {
res.send(docs);
});