此代码有一个集合MenuItems,需要根据登录用户配置文件中的值进行过滤, db.users.find({}); out put是
“个人资料”:{“menuGroup”:“a”}
但我收到错误:
Meteor.userId只能在方法调用中调用。在发布函数中使用this.userId。
来自流星服务器终端。问题行标记在下面代码的末尾。为什么错误以及如何解决?感谢
/////////////////////////////////////
// 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">></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});
});
答案 0 :(得分:0)
我认为你需要更换
Meteor.user()
类似
Meteor.users.findOne({_id: this.userId})
内部发布
...尝试...
Meteor.publish('menuItems', function(){
if (!this.userId) return null;
var menuGroup = Meteor.users.findOne({_id:this.userId}).profile.menuGroup;
return MenuItems.find({group: menuGroup});
});