gpt4 book ai didi

node.js - 如何使用家长 ID 添加家长姓名及其姓名

转载 作者:太空宇宙 更新时间:2023-11-04 00:13:05 25 4
gpt4 key购买 nike

我有以下数组,保存在数据库中。我想修改它以如下所示显示其与 localeName 键中的父级的层次结构。

var allLocales = [
{
id: 123,
localeName: 'Test',
parentId: null
},
{
id: 456,
localeName: 'Test 1',
parentId: 123
},
{
id: 789,
localeName: 'Test 2',
parentId: 456
}
]

我想通过使用其父级更改其显示名称来将上面的数组更改为以下数组。:

allLocales = [
{
id: 123,
localeName: 'Test',
parentId: null
},
{
id: 456,
localeName: 'Test > Test 1',
parentId: 123
},
{
id: 789,
localeName: 'Test > Test 1 > Test 2',
parentId: 456
}
]

最佳答案

如果您使用的是 mongo 3.4+,请尝试此聚合

您可以使用$graphLookup进行分层查询$graphLookup

db.locales.aggregate(
[
{$graphLookup : {
from : "locales",
startWith : "$parentId",
connectFromField : "parentId",
connectToField : "id",
as : "parents"
}
},
{$addFields : {localeName : {$substr : [{$concat : [{$reduce : {input : "$parents", initialValue : "", in : {$concat : ["$$value", " > ", "$$this.localeName"]}}}, " > " ,"$localeName"] }, 3 , 1000]}}},
{$project : {parents : 0}}
]
).pretty()

收藏

> db.locales.find()
{ "_id" : ObjectId("5a73dead0cfc59674782913a"), "id" : 123, "localeName" : "Test", "parentId" : null }
{ "_id" : ObjectId("5a73dead0cfc59674782913b"), "id" : 456, "localeName" : "Test 1", "parentId" : 123 }
{ "_id" : ObjectId("5a73dead0cfc59674782913c"), "id" : 789, "localeName" : "Test 2", "parentId" : 456 }
>

结果

> db.locales.aggregate( [ {$graphLookup : { from : "locales", startWith : "$parentId", connectFromField : "parentId", connectToField : "id", as : "parents" } }, {$addFields : {localeName : {$substr : [{$concat : [{$reduce : {input : "$parents", initialValue : "", in : {$concat : ["$$value", " > ", "$$this.localeName"]}}}, " > " ,"$localeName"] }, 3 , 100]}}}, {$project : {parents : 0}} ] ).pretty()
{
"_id" : ObjectId("5a73dead0cfc59674782913a"),
"id" : 123,
"localeName" : "Test",
"parentId" : null
}
{
"_id" : ObjectId("5a73dead0cfc59674782913b"),
"id" : 456,
"localeName" : "Test > Test 1",
"parentId" : 123
}
{
"_id" : ObjectId("5a73dead0cfc59674782913c"),
"id" : 789,
"localeName" : "Test > Test 1 > Test 2",
"parentId" : 456
}

关于node.js - 如何使用家长 ID 添加家长姓名及其姓名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48575378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com