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

174
Views
Cómo $coincidir con un campo condicionalmente en mongo DB

Tengo el siguiente esquema:

 User: { ...otherFields, isDumb: false, type: "A" // could be "A", "B", or "C" }

Quiero buscar a todos los usuarios dumb de forma predeterminada y buscar por type solo si el type se pasa a través de los parámetros.

 static async getUsers(req: any, res: Response) { const { type = "" } = req.params; const queryPipeline = [ { $match: { isDumb: true, type: // I want to only filter by type if the param is passed in } } ] const users = await User.aggregate(queryPipeline);

Entonces, si mis datos fueran:

 [ { ...otherFields, isDumb: false, type: "A" }, { ...otherFields, isDumb: true, type: "B" }, { ...otherFields, isDumb: true, type: "C" } ]

y req.params.type era "B", debería volver:

 [ { ...otherFields, isDumb: true, type: "B" } ],

si req.params.type no estaba undefined , debería obtener todos los usuarios dumb

 [ { ...otherFields, isDumb: true, type: "B" }, { ...otherFields, isDumb: true, type: "C" } ]
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

solo tienes que construir un objeto y pasarlo para que coincida

 const matchParams = req.params.type ? {isDumb:true,type:req.params.type } : {isDumb:true }
about 4 years ago · Juan Pablo Isaza Report

0

Puedes crear el objeto usando JS:

 const params = "A" // get req.params as you want let query = {$match:{isDumb:true}} if(params) query.$match.type = params console.log(query)

about 4 years ago · Juan Pablo Isaza Report

0

Primero, no necesita usar Aggregation Framework para una consulta de búsqueda simple. Puede usar el método de find en su lugar.

En segundo lugar, considere el enfoque donde inicializa el filtro con isDumb: true y agrega una nueva propiedad de type solo si existe req.params.type .

 let filter = { isDumb: true }; if(req.params.type) filter.type = req.params.type; const users = await User.find(filter);
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!