Home > Back-end >  Mongoose filter data by object dynamic key
Mongoose filter data by object dynamic key

Time:11-28

I have this schema

 _id: 637c96369088ef201f1a0924,
  timestamp: 1669109220,
  date: '2022-11-19',
  rates: {
    ALU: 13.467843419485,
    IRD: 0.00025380710659898,
    IRON: 351.21258466244,
    LCO: 0.62255678407529,
    LEAD: 15.222537878788,
    NI: 1.3163568621028,
    RUTH: 0.1,
    TIN: 1.5148619686393,
    USD: 1,
    XAG: 0.047328809297387,
    XAU: 0.00057311770347523,
    XCU: 4.4456793553765,
    XPD: 0.00055066079295154,
    XPT: 0.001010101010101,
    XRH: 0.000074626865671642,
    ZNC: 10.092283737024
  },
  __v: 0
}  

and I need to create an API that gets one of the rate's key and return the value. I'm trying to create a dynamic query on mongoose, but I keep getting a null object.

if I write the query like this:

await Metals.findOne({ 'rates.RUTH' : { $ne: null }} ).sort({ date: -1 }).exec

I get the right obj. but how to I change RUTH to be the dynamic key I got from the client?

I tried to do:

rates.${metalType} but it returned null as well

CodePudding user response:

Eventually, I solved it this way:

const q:any={ }
q['rates.'   metalType as keyof object] = { $ne: null }
await Metals.findOne( q ).sort({ date: -1 }).exec

CodePudding user response:

// here is the payload
{
     "key":"RUTH"
}

//pass the key you want to search in DB like RUTH OR IRD etc.
let key=req.body.key
let find={}

// here the key variable will hold the inner key of rates Object
find["rates." key]= { $ne: null }
await Metals.findOne(find).sort({ date: -1 }).exec
  • Related