正在尝试用JavaScript编写递归异步搜索



我正试图编写一些代码来搜索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都是一个节点。

我没有过多地研究您的代码,因为我坚信如果可能的话,让您的数据库为您完成工作。

在本例中,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"
}
}
])

Mongo游乐场

如果出于任何原因,你想把它保存在代码中,那么我会看看你的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);

多次处于同一级别。另外,我无法理解您的底部退货声明,我觉得可能存在问题。

最新更新