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

91
Vistas
Find documents with property containing dynamic keys

I'm having some doubts to filter data of some documents that haves a mixed field, I've noticed mongoose takes mixed fields not as a object, but as a array of 'any' data, or something like that, I'm on a research yet, well, my schema looks like the example below:

export const ProductSchema = createSchema({
        active: Type.boolean({ default: true }),
        available: Type.boolean({ default: true }),
        balance: Type.number({ default: 0 }),
        typeMerc: Type.mixed({ default: {} })
    }, { timestamps: true });

For example, I need to find documents that my typeMerc object contains the 'ad0a' key (inside typeMerc), my documents look like this:

{
    _id: ObjectId('6115b8e219f684ac15823')
    active: true
    available: true
    balance: 12
    typeMerc: {
        ad0a: {
            props: "faa0e"
            data: "anyString"
        },
        f0ea: {
            props: "fa45d",
            data: "anyString"
        }
    }
}

If i try on compass the code below, I get the data correctly:

{ 'typeMerc.ad0a': { $exists: true }}

Then, on my code I've tried something like:

const searchId = 'ad0a'
Product.find({ `typeMerc.${searchId}`: { $exists: true } })
Product.find({ `typeMerc.$.${searchId}`: { $exists: true } })
Product.find({ typeMerc[`${searchId}`]: { $exists: true } })
Product.find({ typeMerc[searchId]: { $exists: true } })

But, without success.

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

You have to put the string inside square brackets.

const searchId = 'ad0a'
Product.find({ [`typeMerc.${searchId}`]: { $exists: true } })
about 4 years ago · Santiago Gelvez 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