mongodb - mongo db inner join + 过滤加入文件
问题描述
我有 3 个文档:边界、角色和用户,每个用户有多个角色和一个边界,每个角色有 1 个边界。用户:
{
uuid: String,
name: String,
rolesBoundary: [
roles: [String], // this is the roles the user has for this boundary
boundary: String // this is the uuid of the boundary
]
}
角色:
{
uuid: string,
name: String
}
边界:
{
name: String,
uuid: String
}
我想显示一个边界列表,并且我想再包含一个字段,即登录用户的角色。这是我到目前为止所做的:
{
await BoundaryModel.aggregate([
{
$graphLookup: {
from: 'users',
startWith: '$uuid',
connectFromField: 'uuid',
connectToField: 'boundaryAccess.roles',
as: 'roles'
}
}
]);
}
我知道这是错误的,因为我没有过滤登录用户并且角色数组为空。请问有什么建议吗?
解决方案
通过几次尝试找到了它,我不应该使用图形查找,而是使用查找
exports.getUserBoundaries = async (id) => {
const boundariesList = await BoundaryModel.aggregate()
.lookup({
from: "users",
localField: "uuid",
foreignField: "rolesBoundary.boundary",
as: "user_doc"
})
.match({
$or: [
{"user_doc.uuid": {$exists: false}}, // get result even if the boundary
// doesn't have a uuid which is what
// I want because I want all boundaries
{"user_doc.uuid": id} // and we get also the boundaries with current user id
]
})
推荐阅读
- azure-iot-hub - 使用数组的 Azure 流分析作业
- java - 使用 logstash 配置将 JSON 数据加载到 Elasticsearch 和 Kibana [ConfigurationError: translation missing]
- google-maps - 无法在地理编码函数内分配组件变量值
- c# - ResourceDictionary 中的 OnPlatform 引发错误“属性‘默认’设置不止一次”
- nfc - 加密 NFC 微芯片:JavaCard 还是专用固件?
- spring - JsonInclude 如何仅在未分配时才忽略默认值布尔值
- laravel - 无法在 laravel 5.4 中上传图片
- sql-server-2012 - 如果在任何行的开始日期和结束日期之间,请选择日期
- macos - CMake Mac:使用自定义命令/目标创建通用二进制文件
- regex - 在 Rust 中为正则表达式组合多个字符串时出现“十进制文字为空”