Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

106
Vistas
Mongoose / MongoDB - Query by Array in another document

Is there a way to make a query dependent on another document from another schema in mongoose?

Say I have a user with a list of projects and I want to find a project by ID only if the provided user has the projectId in its list of projects.

Project Schema (extends from Document):

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

User Schema (extends from Document):

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

So I would like to get the project that has the ID and which in the database is within the projectIds array of the user.

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 Respuestas
Responde la pregunta

0

You can do this with aggreagte and lookup

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda