[英]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){
});
您可以嘗試以下方法
let age = 'whateverUserSpecifiesAge'; let email = 'whateverUserSpecifiesEmail'; let userId = 'whateverUserSpecifiesUserId';
注意:它們不一定都應該有一個值,其中一些可以是未定義的,這就是動態查詢的全部內容
let whereCondition = [] if (age) { whereCondition.push({ 'age': age }) } if (email) { whereCondition.push({ 'email': email }) } if (userId) { whereCondition.push({ 'userId': userId }) }
User.find().or(whereCondition).then(users => { /*logic here*/ }).catch(error => { /*error logic here*/ })
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.