gpt4 book ai didi

node.js - 推荐的数据结构(不查询 node.js 中的嵌套数据)

转载 作者:搜寻专家 更新时间:2023-10-30 20:56:15 25 4
gpt4 key购买 nike

Mongo-DB 不支持在嵌套结构中使用通配符进行查询。

在一个看起来像这样的数据结构中:

Courses = [{
'name': 'Learning node.js in 1 day',
'roles': {
'team': { subscribed: [ 'User1' ] },
'participant': { subscribed: [ 'User1', 'User2' ] },
'host': { optional: true, subscribed: [] }
}
}]

我们需要通配符查找来查找不同角色的订阅者,以免使用这样的查询:

{ $or : [ 
{"roles.team.subscribed": 'User1'},
{"roles.participant.subscribed": 'User1'}
{"roles.host.subscribed": 'User1'}
]}

无论如何,如果我们有一个开放的角色列表,这将不起作用。

如果我们把它改成这样:

'roles':  ['team', 'participant', 'host'],
'subscribed': [
{'user':'User1', 'roles': ['team', 'participant']},
{'user':'User2', 'roles': ['participant']}
]

然后找到类(class)的所有参与者同样困难。无论哪种方式,我们都很难找到用户订阅的所有类(class)。

我们考虑为订阅创建一个单独的集合(回到关系):

{user_id: 'User1', course_id: '456', role: 'participant'}
{user_id: 'User1', course_id: '456', role: 'team'}
{user_id: 'User2', course_id: '456', role: 'participant'}

什么是最佳实践?我们希望能够进行各种不同类型的查询,如果它被埋在嵌套结构中似乎很困难......认为这是 mongoDB 中数据结构的一个基本问题。

最佳答案

如果您不想更改结构,我想我会使用聚合框架来做类似的事情。如果您的角色中的字段不是很多并且用户不能完全管理,在这种情况下,我建议您在角色中使用数组并将其展开。让我们来看看你的第一个结构:

Courses = [{
'name': 'Learning node.js in 1 day',
'roles': {
'team': { subscribed: [ 'User1' ] },
'participant': { subscribed: [ 'User1', 'User2' ] },
'host': { optional: true, subscribed: [] }
}
}]

以这种方式项目领域:

姓名、角色.团队、角色.参与者、角色.主持人

所以你最终会得到这个结构

Courses = [{
'name': 'Learning node.js in 1 day',
'roles.team.subscribed': [ 'User1' ] ,
'roles.participant.subscribed': [ 'User1', 'User2' ] ,
'roles.host.subscribed': subscribed: []
}
}]

然后你可以unwind subscribed field并得到一个订阅的笛卡尔积,你需要unwind 3次:

Courses = [
{
'name': 'Learning node.js in 1 day',
'roles.team.subscribed.values': 'User1' ,
'roles.participant.subscribed.values': 'User1',
'roles.host.subscribed.values': ''
}
},
{
'name': 'Learning node.js in 1 day',
'roles.team.subscribed.values': 'User1' ,
'roles.participant.subscribed.values': 'User2',
'roles.host.subscribed.values': ''
}
}

]

最后你可以分别匹配每个角色。

当然要用到聚合框架,需要时间去适应。

关于node.js - 推荐的数据结构(不查询 node.js 中的嵌套数据),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20409838/

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