node.js - 无法找出 mongo 查询
问题描述
我能够到达我能够到达这里的地步:
我希望createdBy成为一个对象(从“用户集合”中查找)并填充firstName和lastName字段。
输出(到目前为止)
{
"workspaceName" : "My first workspace",
"projects" : [
{
"_id" : ObjectId("60857689d2744351901ada70"),
"resources" : [ ],
"status" : false,
"createdAt" : ISODate("2021-04-25T14:02:15.159Z"),
"projectName" : "First project",
"workspace" : ObjectId("60857673d2744351901ada6e"),
"createdBy" : ObjectId("607dc72f0eb1512830b44e57"), // < == here
"__v" : 0
}
]
}
我的查询
db.userworks.aggregate([
{
$match: {
user: ObjectId('607dc72f0eb1512830b44e57'),
workspace: ObjectId('60857673d2744351901ada6e'),
},
},
{ $project: { _id: 0 } },
{
$lookup: {
from: 'workspaces',
localField: 'workspace',
foreignField: '_id',
as: 'workspaces',
},
},
{ $unwind: '$workspaces' },
{
$project: {
workspaceName: '$workspaces.name',
projects: '$workspaces.projects'
},
},
{
$lookup: {
from: 'projects',
localField: 'projects',
foreignField: '_id',
as: 'projects',
},
}
]).pretty()
如果我使用LOCALFIELD作为“ projects.createdBy ”对用户集合进行另一次查找,它会在输出底部添加另一个对象。
我希望它在每个项目详细信息(数组)中
架构:
// userworks
{
user: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'User',
required: true,
},
workspace: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'Workspace',
required: true,
}
}
// workspaces
{
owner: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'User',
required: true,
},
name: {
type: String,
required: true,
},
projects: [
{
type: mongoose.SchemaTypes.ObjectId,
ref: 'Project',
default: [],
},
],
}
// users
{
firstName: { type: String, required: true },
lastName: { type: String, required: true },
}
解决方案
推荐阅读
- docusignapi - 使用 API 发送文档并设置 SignHere AnchorString 与字段定位器
- c++ - 在主函数内部和外部声明变量之间的区别
- python - 从具有不同列长度的熊猫中读取_csv
- angular - rxjs:如何从 catchError 中返回另一个 observable 的结果
- sql - where 子句中的多项选择
- c# - 在 C# 中执行具有复杂输出的 cmd 命令
- reactjs - 如何在 URL 中传递值以及如何在 React JS 中从 URl 获取值
- html - 从本地文件系统打开文件时如何创建下载链接
- java - ZonedDateTime 作为 Epoch 时间而不是 Spring App 中的标准字符串返回
- css - 更改颜色 Office UI Fabric 切换