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

81
Views
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 answers
Answer question

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