Fred J.
Fred J.

Reputation: 6029

User profile value as a value in collection find query

This code has a collection MenuItems which needs to be filtered according to a value in the logged in user profile, db.users.find({}); out put is

"profile" : { "menuGroup" : "a" }

but I am getting error:

Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.

from the meteor server terminal. The problem line is marked at the end of the code below. Why is the error and how can it be fixed? Thanks

/////////////////////////////////////
//       client
/////////////////////////////////////
<template name="mainMenu">
  <div class="container">
    <div class="row">
      <section class="col-xs-12">
        <div class="list-group menuItems">
          {{#each menuItems}}
            <li data-template="{{menuItem}}" role="presentation">
              <a href="#" class="list-group-item menuItem">
                <img src="/abc.png">
                {{menuItem}} <span class="badge">&#x3e;</span>
              </a>
            </li>
          {{/each}}
        </div>
      </section>
    </div>
  </div>
</template>

Template.mainMenu.onCreated(function () {
  var template = this;
  template.handler = template.subscribe('menuItems');
});

Template.mainMenu.helpers({
  menuItems: function () {
    return MenuItems.find();
  }
});

Template.mainMenu.onDestroyed(function () {
  var template = this;
  if (template.handler && template.handler.stop) template.handler.stop();
});

/////////////////////////////////////
//       server code
/////////////////////////////////////    
var items =
  [
    {menuItem: "task1", group: "ab"},
    {menuItem: "task2", group: "ab"},
    {menuItem: "task3", group: "b"},
    {menuItem: "task4", group: "a"},
    {menuItem: "task5", group: "a"},
    {menuItem: "task6", group: "a"},
    {menuItem: "task7", group: "b"},
    {menuItem: "task8", group: "b"},
    {menuItem: "task9", group: "b"},
    {menuItem: "login", group: "ab"},
    {menuItem: "logout", group: "ab"}
  ]
if (!MenuItems.find().count()) {
    _.each(items, function (doc) {
        MenuItems.insert(doc);
    })
}

Meteor.publish('menuItems', function(){
  var menuGroup = Meteor.user().profile.menuGroup; //<<<<< problem line
  return MenuItems.find({group: menuGroup});
});

Upvotes: 0

Views: 74

Answers (1)

Alex028502
Alex028502

Reputation: 3814

I think you need to replace

Meteor.user()

with something like

Meteor.users.findOne({_id: this.userId})

inside publish

...try...

Meteor.publish('menuItems', function(){
  if (!this.userId) return null;

  var menuGroup = Meteor.users.findOne({_id:this.userId}).profile.menuGroup;
  return MenuItems.find({group: menuGroup});
});

Upvotes: 0

Related Questions