【问题标题】:Mongoose / MongoDB - Query by Array in another documentMongoose / MongoDB - 在另一个文档中按数组查询
【发布时间】:2021-11-12 17:12:43
【问题描述】:

有没有办法使查询依赖于 mongoose 中另一个模式的另一个文档?

假设我有一个拥有项目列表的用户,并且我希望仅当提供的用户在其项目列表中具有 projectId 时才通过 ID 查找项目。

项目架构(从文档扩展):

const projectSchema = new Schema<ProjectSchema, ProjectModel>(
  {
    name: { type: String, required: true, trim: true },
    description: { type: String, default: '', trim: true },
  },
  {
    collection: 'project',
    timestamps: true,
    versionKey: false,
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  },
);

用户架构(从文档扩展):

const userSchema = new Schema<UserSchema, UserModel>(
  {
    email: { type: String, unique: true, required: true, trim: true },
    projectIds: { type: [Schema.Types.ObjectId], default: [], ref: 'Project' },
  },
  { collection: 'user', timestamps: true, versionKey: false },
);

所以我想获取具有 ID 并且在数据库中位于用户的 projectIds 数组中的项目。

export async function findProjectForUser(user: User, id: string) {
   // get the user from DB by user id (security reasons)
   const dbUser = await UserModel.findById(user.id);
   if(!dbUser) return undefined; // 401

   // check if user has id in projectId array
   const hasProject = dbUser.projectIds.find(pId => pId === id);
   if(!hasProject) return undefined // 401

   // fetch project from db by id
   const project = await ProjectModel.findById(id);
   
   // => can I merge the two queries into one?
  
   return project
}

【问题讨论】:

  • 您是否尝试过使用聚合?

标签: javascript typescript mongodb mongoose


【解决方案1】:

您可以使用 aggreagtelookup 来做到这一点

db.users.aggregate([    
    { $match: { _id: user.id }},
    { $unwind: "$projectIds"},
    { $lookup: { 
        from: ProjectModel.collection.name,
        as: "project",
        pipeline: [
            { $match: { _id: id }}
        ]
    }}
])
.map(doc => doc.project);

【讨论】:

    猜你喜欢
    • 2017-02-24
    • 2013-07-15
    • 2020-08-02
    • 2017-10-01
    • 2020-12-04
    • 2020-03-28
    • 2019-08-01
    • 1970-01-01
    • 2020-06-11
    相关资源
    最近更新 更多