I am trying to search for documents in mongodb that include a specific search string input by the user. Collection that i am trying to search in is named imported_products and my mongodb document structure looks like following.
{
┃ _id: 61add3b16c9e0008e6ad325b,
┃ shop: 'someshop',
┃ shopUserData: { name: 'LoTesting', email: 'vixen@yahoo.com' },
┃ productData: {
┃ title: 'Eyglo 3-in-1 Head Strap for Oculus Quest 2 with Face Silicone Cover & Controllers Grips Covers',
┃ price: 45.99,
┃ priceWithCurrency: '$45.99',
┃ images: [Array],
┃ ASIN: 'B08TWJJ3ZW',
┃ marketPlace: 'www.amazon.com',
┃ settings: [Object],
┃ shopifyProductId: 87187377131097
┃ },
┃ created_at: 2021-12-06T09:11:13.327Z
┃ },
┃ {
┃ _id: 61ae236cac749b088d427497,
┃ shop: 'shomeshop',
┃ shopUserData: { name: 'LoTesting', email: 'test@gmail.com' },
┃ productData: {
┃ title: 'Xbox Series X',
┃ description: 'Amazon Prime customers will have priority access to the Xbox Series X until November 24, 2021.',
┃ price: 'price not available',
┃ priceWithCurrency: 'price not available',
┃ images: [Array],
┃ ASIN: 'B08H75RTZ8',
┃ marketPlace: 'www.amazon.com',
┃ settings: [Object],
┃ shopifyProductId: 5736818278172
┃ },
┃ created_at: 2021-12-06T14:51:24.755Z
┃ },
What i need is that, for a specific shop, i need to look up into all of the documents of that shop and inside title property of productData field, i need to search for the query string input by user. So, i need to use $and condition to lookup for the shop and matching query string inside the title property and then i need to return all of the documents matching the condition.
I tried following but i keep getting empty array.
const regex = RegExp("/.*" + searchQuery + ".*/");
response = await db
.collection("imported_products")
.find({
$and: [
{ shop: shop },
{ "productData.title": { $regex: regex, $options: "i" } },
],
})
.toArray();
Please guide me to the right path. I am using koa.js for server and next.js for client side.