首页 > 解决方案 > 无法找出 mongo 查询

问题描述

我能够到达我能够到达这里的地步:

我希望createdBy成为一个对象(从“用户集合”中查找)并填充firstNamelastName字段。

输出(到目前为止)

{
        "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 },
}

标签: node.jsmongodbtypescriptmongoosenosql

解决方案


推荐阅读