Reputation: 247
I have the following code:
var keyExp = 'experienceCat' + req.param('category');
User.native(function(err,collection)
{
collection.find({'_id':{$in:usersArray}},{fields:{'name':1,'avatar':1,'fbId':1,'country':1,keyExp:1}}).toArray(function (err,userProfiles)
{
res.send(userProfiles);
});
});
The problem is that instead of changing the keyExp to its current value (which should be "experienceCat0"
for example) it's actually trying to find the column with the name "keyExp"
which of course doesn't exist.
How should the code look like to be able to read the correct column based on the req.param('category')
parameter?
Upvotes: 0
Views: 52
Reputation: 382324
Here's how you should do it today:
var fields = {'name':1,'avatar':1,'fbId':1,'country':1};
fields['experienceCat' + req.param('category')] = 1;
User.native(function(err,collection){
collection.find({'_id':{$in:usersArray}},{fields:fields}).toArray(function (err,userProfiles)
{
res.send(userProfiles);
});
});
With ES6 you'll be able to express that in a more concise way:
var keyExp = 'experienceCat' + req.param('category');
User.native(function(err,collection){
collection.find( ... ,'fbId':1,'country':1,[keyExp]:1}}).toArray(function (err,userProfiles)
^^^^^^^^
{
res.send(userProfiles);
});
});
Upvotes: 1