2

How can I query mongodb using a variable as the key I'm searching for?

The data:

const schedule = {
  day0: [10, 1440],
  day1: [10, 1440],
  day3: [10, 1440],
  day6: [10, 1440],
}

The query

User.find({ `schedule.${varHere}` { $exists: true}}, (err, users) => {
  console.log(users)
})
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Braxton C
  • 47
  • 1
  • 7
  • Possible duplicate of [How do I add a property to a JavaScript Object using a variable as the name?](http://stackoverflow.com/questions/695050/how-do-i-add-a-property-to-a-javascript-object-using-a-variable-as-the-name) – Matt Aug 22 '16 at 21:49

1 Answers1

10

You need to set up a object first either using ES6 computed propery names

const query = { [`schedule.${varHere}`]: { $exists : true } };

or using an expression as a property name

const query = {};
query[`schedule.${varHere}`] = { $exists: true };

then

User.find(query, (err, users) => {
  console.log(users)
})
Carlos Sultana
  • 709
  • 5
  • 11
  • Thank you very much man User.find({[`schedule.${day}`]: {$exists: true}}, (err, users) => { console.log(users) }) worked like a charm – Braxton C Aug 22 '16 at 21:54