Specifying fields dynamically in find query


#1

Good day,
I would like to observe changes on a nested profile property in the Meteor.users collection
My user profile field contains the following nested field:
viewsettings: {‘projectAid’:{showdata:true, showgraph:true}, ‘projectBid’:{showdata:false, showgraph:false}}

The user can switch between project viewsettings by using the relevant projectid. However, I cannot get the correct field value in the code below when the user interface toggles the nested ‘showdata’ field.

Template.desktop.onCreated(function(){
instance.autorun(function(){
var projectid = Meteor.users.find(Meteor.userId(), {fields:{‘profile.activeproject’:1}}).fetch()[0].profile.activemodel;

   // This does not work: var query = Meteor.users.find(Meteor.userId(),{fields:{'profile.viewsettings.'+projectid+'.showdata'}});
   // I saw on forums that I need to build a selector object, but my attempt below only returns the document _id and not the field...
    var showdata={};
    showdata['profile']={}
    showdata['profile'][projectid]={}
    var query = Meteor.users.find(Meteor.userId(), {fields:{showdata:1}});

    query.observe({
        changed: Meteor.myFunction
    });
    
});

})

If I do a console.log on the fetched query I typically get this:
Object { _id: “ZQ97HY9AtqrtJDna3” }
I am looking for something like this:
Object { profile: Object, _id: “ZQ97HY9AtqrtJDna3” }

Any advice will be greatly appreciated as to how I can dynamically retrieve a nested field value.


#2

Does it relate to this?:


#3

Hi Steve,
My problem is to correctly formulate the projection (fields) filter, where a part of the filter comes from a variable.
In the above example the keys ‘game’ and ‘blah’ is known. In my problem the projection filter needs to be able switch from ‘viewsettings.XW34jkebc.showdata’ to ‘viewsettings.U25ghSDSD.showdata’ to ‘viewsettings.P67GHadsasd.showdata’ to etc…


#4

could not it be just typo as
fields: {'something': 1} and you dont write that 1 there ?


#5

First, You could fetch only top-level fields with {fields: <>} - means {fields: {'profile': 1}} is valid but {fields: {'profile.views.counts': 1}} is invalid.
Second, you can not create dynamic observer. But you may observe some chunk of collection (I mean kind of wide filter) and then do any additional checks inside observe -> changed