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

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

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 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