2

I have these codes now:

OneCollection.find({}, {fields: {'oneFiled.child1': 1}});
OneCollection.find({}, {fields: {'oneFiled.child2': 1}});

But I want to give a dynamically child filed name.

let childfield = "child1";
OneCollection.find({}, {fields: {'oneFiled.childfield': 1}});  // How to write this one?

How can I dynamically give the filed name? Thanks

Hongbo Miao
  • 45,290
  • 60
  • 174
  • 267

2 Answers2

3

Use the bracket notation to construct the field object as follows:

var childfield = "child1",
    options = { fields: {} };

options["field"]["oneField."+childfield] = 1;
OneCollection.find({}, options); 
chridam
  • 100,957
  • 23
  • 236
  • 235
2

Like this ?

let childField = 'child1';
let listFields = {};
listFields['oneField.'+childField]=1;
OneCollection.find({}, {fields: listFields });
Alain P
  • 66
  • 5