Home > OS >  Find documents with property containing dynamic keys
Find documents with property containing dynamic keys

Time:07-20

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.

CodePudding user response:

You have to put the string inside square brackets.

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