[英]Adding $and and $or queries to a structure for a MongoDB query - must be a non empty array
我正在嘗試將多個查詢組合到一個 object 中:用戶可以從預選的選項和 select 或者 and 或 or 運算符構建查詢。 查詢都正確輸出,但是當將它們放入 object 時,我得到“錯誤:$and/$or/$nor must be nonempty array”。
例如,假設我們有查詢 a AND b AND c AND d AND e output 應該是:{$and[a,$and:[b,$and:[c,$and:[d,e]]]]}這樣如果他們 select 另一個操作員,操作仍然保持不變
這是代碼:
function nestOps(ops, queries) {
let queryObj = {};
if (ops.length > 1) {
let querySet = {};
querySet[`$${ops[ops.length - 1]}`] = [queries[ops.length - 1], queries[ops.length]];
for (let i = ops.length - 2; i > 0; i--) {
let next = {};
next[`$${ops[i]}`] = querySet;
querySet = {};
let nextIdx = i - 1;
if (nextIdx > 0) {
querySet[`$${ops[nextIdx]}`] = [queries[i], next];
i--;
}
else {
querySet = next;
}
}
queryObj[`$${ops[0]}`] = [querySet, queries[0]];
}
else {
queryObj[`$${ops[0]}`] = [...queries];
}
return queryObj;
}
我已經嘗試通過遞歸來完成它,但是我的堆棧非常臃腫(即使堆棧大小增加了)並且我看不到如何使用拖尾方法(“return nextCall()”),因為我必須返回上一個查詢和或 orred如果沒有先分配任務,我真的無法做到這一點。
這是控制台 output:
Output Object
$and: Array(2)
0:
$and: Array(2)
0: {questions: {…}}
1:
$and: // could be an error here but, I don't understand why
$and: Array(2)
0: {$or: Array(2)} //this happens due to a query, it is not an error
1: {questions: {…}}
Operators
["and", "and", "and", "and"]
Queries
(5) [{…}, {…}, {…}, {…}, {…}]
0: {questions: {…}}
1: {completedAt: {…}}
2: {questions: {…}}
3: {$or: Array(2)}
4: {questions: {…}}
您可以使用單個$and
$and
{ property: { $and: [ {filter}, {filter} ] }}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.