我正在嘗試使用過濾器撰寫一個簡單的 API 來從資料庫中獲取用戶。我想通過給定的特定引數過濾此資料,這些引數是可選的:
如何通過查詢無引數、單引數和多引數的 API 來靈活地從資料庫中獲取資料?
控制器:-
方法一
const articles = await userTable.find({
'$or': [{
'name': req.query.name
},
{
'address': req.query.address
},
{
'address': req.query.address,
'name': req.query.name
}]
});
當我被單個引數擊中時它給出正確的回應但是當被多個引數擊中時http://localhost:4000/api/filter?name=abhishek&address=tejaji它給出錯誤的回應但我只想要包含名稱 abhishek 和地址 tejaji 的那一行
方法二
const articles = await userTable.find({
name:req.query.name,address:req.query.address,
$or: [ { name:req.query.name }, {address:req.query.address } ]
});
當我被單個引數擊中時它給出 0 回應但是當被多個引數擊中時http://localhost:4000/api/filter?name=abhishek&address=tejaji它給出正確的回應但我也想要來自單個引數的結果
方法三
const articles = await userTable.find({
'usertables': {
$elemMatch: {
'name': req.query.name,
'address': req.query.address
}
}
});
當我點擊單個引數http://localhost:4000/api/filter?name=abhishek或多個http://localhost:4000/api/filter?name=abhishek&address=tejaji 它總是給出表中的所有行,這是錯誤的。
路線:-
router.get("/filter", userController.filterMethod);
uj5u.com熱心網友回復:
嘗試使用filter物件并根據存在的引數向其添加鍵:
const { name, address } = req.query;
const filter = {}
if (name) {
filter.name = name
}
if (address) {
filter.address = address
}
const articles = await userTable.find(filter);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/391895.html
上一篇:MongoDB嵌套查詢問題:未捕獲的例外:SyntaxError:missing:afterpropertyid:
