user3768533 user3768533 - 2 months ago 6
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
'name'
. However, if I try to pass
'name'
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
findOne()
function while making the attribute argument variable, i.e. I could pass in
'name'
,
'age'
,
'city'
, etc.

Answer

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