How to set the key of the object from query params in model.find

Viewed 114

I want to make the key of the object from query params in the model.find method.

I have already tried this:

moongoose.model.find({ req.query.type : req.params.tid})

and this:

let type = req.query.type
moongoose.model.find({type  : req.params.tid})
2 Answers

You need to use square brackets if you want to use the variable value as key:

const type = req.query.type;
mongoose.model.find({[type]: req.params.tid});
An example:
const key = 'myKey';
const obj = { [key]: 'value' };

console.log(obj);

You should always use computed property names when creating an object with dynamic key names.

function findStuff() {
  const type = req.query.type
  const result = moongoose.model.find({type  : req.params.tid});
  return `${result}`;
}

const myObj = {
  a: 'a',
  b: 'b'
  [findStuff()]: 'something'
};
Related