我正在嘗試在 mongodb 中搜索包含用戶輸入的特定搜索字串的檔案。我要搜索的集合名為imported_products,我的mongodb 檔案結構如下所示。
{
┃ _id: 61add3b16c9e0008e6ad325b,
┃ shop: 'someshop',
┃ shopUserData: { name: 'LoTesting', email: '[email protected]' },
┃ 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: '[email protected]' },
┃ 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
┃ },
我需要的是,對于特定商店,我需要查找該商店??的所有檔案以及 productData 欄位的 title 屬性,我需要搜索用戶輸入的查詢字串。因此,我需要使用 $and 條件在 title 屬性中查找商店和匹配的查詢字串,然后我需要回傳與條件匹配的所有檔案。
我嘗試跟隨,但我不斷得到空陣列。
const regex = RegExp("/.*" searchQuery ".*/");
response = await db
.collection("imported_products")
.find({
$and: [
{ shop: shop },
{ "productData.title": { $regex: regex, $options: "i" } },
],
})
.toArray();
請引導我走上正確的道路。我在服務器端使用 koa.js,在客戶端使用 next.js。
uj5u.com熱心網友回復:
您不需要手動放置$and,因為默認情況下所有條件都匹配。另外你拼錯someshop的shomeshop檔案2,這可能是得到一個空陣列的原因之一。如果文本與輸入的任何部分匹配,則默認情況下您也不需要使用.*in RegExp("/.*" searchQuery ".*/"),正則運算式將回傳 true 并捕獲第一個匹配項。$regex也不需要向運算子傳遞正則運算式。我的建議是searchQuery.replace(/\s /g, ' ')改用。下面的例子應該可以作業。
db.collection("imported_products").find({
shop: shop,
"productData.title": {
$regex: searchQuery,
$options: "i"
}
})
您可以在此處測驗查詢。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/383083.html
標籤:javascript 节点.js MongoDB koa.js
