Categories
JavaScript Answers

How to use a variable as a field name in mongodb-native findOne() with JavaScript?

Spread the love

To use a variable as a field name in mongodb-native findOne() with JavaScript, we call use a computed property name.

For instance, we write

const name = req.params.name;
const value = req.params.value;
collection.findOne({ [name]: value }, (err, item) => {
  res.send(item);
});

to call findOne with an object that has the name value as the property name.

Then we get the result from item in the callback.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *