1

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.

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

glad to help mate :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.