Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda