我正在嘗試撰寫一些代碼來搜索 MongoDB 資料庫中的一堆物件。我想通過 ID 從資料庫中提取物件,然后這些物件具有 ID 參考。程式應該通過這個程序搜索特定的ID,首先從id中獲取物件,然后從物件中獲取id。
async function objectFinder(ID1, ID2, depth, previousList = []) {
let route = []
if (ID1 == ID2) {
return [ID2]
} else {
previousList.push(ID1)
let obj1 = await findObjectByID(ID1)
let connectedID = obj1.connections.concat(obj1.inclusions) //creates array of both references to object and references from object
let mapPromises = connectedID.map(async (id) => {
return findID(id) //async function
})
let fulfilled = await Promise.allSettled(mapPromises)
let list = fulfilled.map((object) => {
return object.value.main, object.value.included
})
list = list.filter(id => !previousList.includes(id))
for (id of list) {
await objectFinder(id, ID2, depth - 1, previousList).then(result => {
route = [ID1].concat(result)
if (route[route.length - 1] == ID2) {
return route
}})
}
}
if (route[route.length - 1] == ID2) {
return route
}
}
我不確定如何使我的代碼像樹搜索一樣作業,每個物件和 ID 都是一個節點。
uj5u.com熱心網友回復:
我沒有過多地研究您的代碼,因為我堅信,如果可能,讓您的資料庫為您完成作業。
在這種情況下,Mongo 有$graphLookup聚合階段,它允許遞回查找。這是一個關于如何使用它的快速示例:
db.collection.aggregate([
{
$match: {
_id: 1,
}
},
{
"$graphLookup": {
"from": "collection",
"startWith": "$inclusions",
"connectFromField": "inclusions",
"connectToField": "_id",
"as": "matches",
}
},
{
//the rest of the pipeline is just to restore the original structure you don't need this
$addFields: {
matches: {
"$concatArrays": [
[
{
_id: "$_id",
inclusions: "$inclusions"
}
],
"$matches"
]
}
}
},
{
$unwind: "$matches"
},
{
"$replaceRoot": {
"newRoot": "$matches"
}
}
])
蒙戈游樂場
如果出于某種原因您想將其保留在代碼中,那么我將查看您的for回圈:
for (id of list) {
await objectFinder(id, ID2, depth - 1, previousList).then(result => {
route = [ID1].concat(result);
if (route[route.length - 1] == ID2) {
return route;
}
});
}
快速瀏覽一下,我可以告訴您正在執行此操作:
route = [ID1].concat(result);
多次處于同一水平。另外我無法理解您的底部退貨宣告,我覺得那里可能存在問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/359911.html
標籤:javascript MongoDB 异步 递归
下一篇:橢圓WPF中的文本框
