我正在做一个项目,并拥有这两个MongoDB集合,团队(持有团队的细节)和支付(持有团队的付款)(严格的1-1关系)。
Payment Schema
{
...
team: { type: Schema.Types.ObjectId, ref: 'Team', unique: true },
...
}对于团队,我有两种选择:
Team1 Schema
{
user_id: { type: Schema.Types.ObjectId, ref: 'User' }
}..。
Team2 Schema
{
user_id: { type: Schema.Types.ObjectId, ref: 'User' }
payment: { type: Schema.Types.ObjectId, ref: 'Payment', unique: true }
}需要:我有一个组件“我的团队”,在这里我需要显示登录用户的所有团队和他的支付状态(是/否)。
问题与Team1模式:,因为我没有对支付的引用,所以我需要再次调用与团队的_id后端,以获得每个团队的支付对象。如果用户有10个团队,那么它将是11个后端呼叫(1个用于团队,接下来10个用于支付状态)。
关于Team2模式的问题:,因为我现在在Team2模式中有了支付_id,所以我可以简单地检查该字段是否存在,以确定它是否已经支付。但现在的问题是,当支付时,我需要更新集合和需要使用事务(在任何失败的情况下回滚),这增加了复杂性,也不支持,除非我设置了副本集。
你能帮我找出最好的办法吗?
提前谢谢。
发布于 2019-01-16 20:53:42
最简单的解决方案就是在支付模式中使用team_id (您已经有了)。
您不需要团队模式中的user_id或payment_id来获得团队支付。您只需在payments表上进行聚合查询,以使团队与支付一起。
因此,考虑到您有一个团队ID,并且您需要团队数据和支付数据,您可以编写一个聚合查询,如下所示,
Team.aggregate([
{
$match: { _id: { $in: list_of_user_ids } } // this will get the teams which match the array of ids
},
{
$lookup: // this will search data from a different collection
{
from: 'payments', // the collection to search from
localField: '_id', // the matching field in the team collection
foreignField: 'team', // matching field in the payment colection
as: 'payment' the name you want to give to the resulting payment object
}
}
])编辑1:我编写的查找完全可以满足您的需要。只是我以为您有一个用户I数组。如果您只有一个用户ID,只需将匹配操作更改为您所编写的
$match: { user_id: currently_loggedin_userId } https://stackoverflow.com/questions/54224181
复制相似问题