user3768533 user3768533 - 1 year ago 45
Javascript Question

Node.js string inside javascript object argument

I'm not really sure how to name this problem but essentially I am using the Mongoose package for MongoDB and the function is not behaving. The function in question is:

var value = 'onetwothree'
model.findOne({ 'name': value }, callback)

which allows me to search the database for the attribute
. However, if I try to pass
in as a variable, the function doesn't work. For example, this doesn't work:

var attribute = 'name'
model.findOne({ attribute: value}, callback)

How do I call the
function while making the attribute argument variable, i.e. I could pass in
, etc.

Answer Source

You can just create the object before passing it into the function and assign the dynamic property using the [] notation:

var query = {};
var attr = 'city';
var val = 'Miami';

// set the dynamic property
query[attr] = val; // { city: 'Miami' }

model.findOne(query, callback)

Or in ES6 (if you're using Babel) you can do it directly with a Computed Property Name:

const attr = 'city';
const val = 'Miami';
const query = { [attr]: val }; // { city: 'Miami' }

model.findOne(query, callback);