Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
Mongoose / MongoDB - Consulta por Array en otro documento

¿Hay alguna manera de hacer que una consulta dependa de otro documento de otro esquema en mongoose?

Digamos que tengo un usuario con una lista de proyectos y quiero encontrar un proyecto por ID solo si el usuario proporcionado tiene el ID del proyecto en su lista de proyectos.

Esquema del proyecto (se extiende desde el documento):

 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 }, }, );

Esquema de usuario (se extiende desde el documento):

 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 }, );

Entonces, me gustaría obtener el proyecto que tiene la ID y que en la base de datos está dentro de la matriz projectIds del usuario.

 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 }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puedes hacer esto conagregación y búsqueda .

 db.users.aggregate([ { $match: { _id: user.id }}, { $unwind: "$projectIds"}, { $lookup: { from: ProjectModel.collection.name, as: "project", pipeline: [ { $match: { _id: id }} ] }} ]) .map(doc => doc.project);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!