Braxton C Braxton C - 3 months ago 9
Node.js Question

Trying to query mongoose with variable as key

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

Answer

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)
})
Comments