簡體   English   中英

ZCCADCDEDB567ABAE643E15DCF0974E503Z 使用多個條件構建動態查詢並將 where 子句值作為變量傳遞

[英]Mongoose dynamic query building with multiple condition and passing the where clause value as variable

我正在嘗試構建具有多個 where 條件的 mongoose 查詢。 場景是用戶可以選擇不同的 where 子句,例如按年齡搜索、按 email 搜索、搜索用戶 ID 等。因此 where 子句會動態變化。

此外,當我在變量中傳遞值時,不會獲取數據。 如果我直接傳遞值,它就可以工作。

任何建議或幫助表示贊賞

如果您的集合字段名和字段值是動態的,您可以嘗試如下

 let searchdata={};

 //this is for example
 let fieldName = "name";
 let fieldValue = "hello"
 
 searchdata[data.fieldName]={ $regex : data.fieldValue || '', $options : 'i'};
 
 
 User.aggregate([{$match:searchdata}],function(err,data){
      
 });

您可以嘗試以下方法

  1. 接受來自用戶的輸入並將它們存儲在變量中。

 let age = 'whateverUserSpecifiesAge'; let email = 'whateverUserSpecifiesEmail'; let userId = 'whateverUserSpecifiesUserId';

注意:它們不一定都應該有一個值,其中一些可以是未定義的,這就是動態查詢的全部內容

  1. 構造一個用於查找用戶的 where 條件。

 let whereCondition = [] if (age) { whereCondition.push({ 'age': age }) } if (email) { whereCondition.push({ 'email': email }) } if (userId) { whereCondition.push({ 'userId': userId }) }

  1. 現在我們已經構建了 where 條件,我們可以找到用戶

 User.find().or(whereCondition).then(users => { /*logic here*/ }).catch(error => { /*error logic here*/ })

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM