I have this code:
let collection = database.collection('Product')
let doc = await collection.find({"Product_Name": /req.query.Product_Name/}).toArray()
console.log(doc)
I have a product (ex) called Test Product (22in)
so I want someone to be able to search Test Product
, and it should come up, however, my code ins't doing that. Is there anything I'm doing wrong?
CodePudding user response:
Since you are trying to provide a regex pattern, need to use $regex
query operator.
let doc = await collection.find({
"Product_Name": {
"$regex": "Test Product",
"$options": "i"
}
}).toArray()
Note: the option i
is for Case insensitivity. You can read more about the operator adn hwo regex matching behaves in the docs.
Side note: Regex matching over a large number of documents is expensive and you could consider bulding an index (text) for the feild where search is required.
See an example playground link here