Braxton C
Braxton C

Reputation: 47

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

Upvotes: 2

Views: 3179

Answers (1)

Carlos Sultana
Carlos Sultana

Reputation: 709

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

Upvotes: 10

Related Questions