我想解釋一下我今天的問題。
目前,我在一個輸入上執行一個過濾器,允許我搜索姓氏和名字,效果非常好
。為了更簡單地閱讀代碼,我洗掉了很多東西,如果有必要引入其他元素,請不要猶豫
我已經洗掉了很多東西。
span class="hljs-keyword">const {
data: packUsersData,
} = useQuery(
[
"pack",
id,
"user"。
...(currentOperatorsIds.length ? currentOperatorsIds : [] )。
值。
],
async()=> {
const getExpr = () => ( {
$expr: {
$or: [
{
$regexMatch: {
input: {
$concat: ["$firstName", " ", " $lastName"]。
},
regex: value,
options: "i"/span>,
},
},
{
$regexMatch: {
input: {
$concat: ["$lastName", " ", " $firstName"]。
},
regex: value,
options: "i"/span>,
},
},
],
},
});
let res = await usersApi.getrs({
pagination: false,
query: {
"role.name": "operator",
_id: { $nin: currentOperatorsIds },
deletedAt: null,
$or: value
? [
{
entities: [],
...getExpr()。
},
{
entities: { $in: id },
...getExpr()。
},
]
: [
{
entities。[],
},
{
entities: { $in: id },
},
],
},
populate: "物體"。
sort: ["lastName", "firstName"]。
});
{
refetchOnMount: true,
}
);
所以我發現讀起來有點太長了,有什么想法可以讓我縮短這一切嗎?
謝謝你的幫助
uj5u.com熱心網友回復:- 你可以減少
entities欄位的$or條件,只要將空陣列和輸入的id連接起來,
let res = await usersApi.getrs({
pagination: false,
query: {
"role.name": "operator",
_id: { $nin: currentOperatorsIds },
deletedAt: null,
entities: { $in: [[], ...id] 。},
...getExpr()
},
populate: "物體"。
排序: ["lastName"/span>, "firstName"/span>]
});
- 如果你想改進正則運算式的條件,你可以嘗試下面的方法,不使用
$expr和聚合運算子,
- 創建一個函式,并將輸入的
searchKeyword和searchProperties設定為你想要的字串陣列 。
function getSearchContiion(searchKeyword, searchProperties) {
let query = {};
if (searchKeyword) {
query = { "$or"/span>: [] };
const sk = searchKeyword.trim().split(" ") 。 map(n => new RegExp(n, "i") )。
searchProperties.forEach(p => {
query["$or"].push({ [p]: { "$in": [...sk] }) 。)
});
}
return查詢。
}
// EX:
console。 log(getSearchContiion("John Doe"/span>, ["firstName"/span>, "lastName"/span>]) 。)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
- 在查詢中使用上述函式 。
let res = await usersApi.getrs({
pagination: false,
query: Object.assign(
{
"role.name"。"operator",
_id: { $nin: currentOperatorsIds },
deletedAt: null,
entities: { $in: [[], ...id] 。}
},
getSearchContiion(value, ["firstName", "lastName"] )
},
populate: "物體"。
排序: ["lastName", "firstName"] 。
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/324510.html
標籤:
