1

如何发布单个对象对我来说似乎不够清楚。请问什么是最好的方法来处理这个。此代码片段不会在视图上显示任何内容。

帮助文件

singleSchool: function () {
   if (Meteor.userId()) {
      let myslug = FlowRouter.getParam('myslug');
      var subValues = Meteor.subscribe('SingleSchool', myslug );
        if (myslug ) {
          let Schools = SchoolDb.findOne({slug: myslug});
          if (Schools && subValues.ready()) {
             return Schools;
          }
       }
   }    
},

发布文件

Meteor.publish('SingleSchool', function (schoolSlug) {
  check( schoolSlug, Match.OneOf( String, null, undefined ) );
    user = Meteor.users.findOne({_id:this.userId})
  if(user) {
    if(user.emails[0].verified) {
      return SchoolDb.findOne({ slug: schoolSlug, userId: {$lt: this.userId}});
    } else {
      throw new Meteor.Error('Not authorized');
      return false;
    }
  }
});

模板文件

<template name="view">
  {{#if currentUser}}
    {{#if Template.subscriptionsReady }}
      {{#with singleSchool}}
        {{singleSchool._id}}
        {{singleSchool.addschoolname}}
      {{/with}}
    {{/if}}
  {{/if}}
</template>
4

2 回答 2

4

正如您所说“此代码片段不会在视图上显示任何内容。 ”好吧,Meteor.publish您需要在里面 return cursor, notarray或任何其他object

所以使用这个代码:

Meteor.publish('SingleSchool', function (schoolSlug) {
  check( schoolSlug, Match.OneOf( String, null, undefined ) );
  var user = Meteor.users.findOne({_id:this.userId});
  if(!user || !user.emails[0].verified) {
        throw new Meteor.Error('Not authorized');
    }
    return SchoolDb.find({ slug: schoolSlug, userId: {$lt: this.userId}},{limit:1});
});

我绝对会建议您阅读如何避免常见错误

于 2017-09-26T13:02:58.970 回答
1

当我只关心单个对象时,我使用流星方法实现它:

Meteor.methods({
    "getSingleSchool":function(schoolSlug) {
        //... check args and user permissions
        return SchoolDb.findOne({ slug: schoolSlug, userId: {$lt: this.userId}});
    },
});

然后在模板中,我在 onCreated 自动运行部分运行此方法:

Template.view.onCreated(function(){
    const instance = this;
    instance.state = new ReactiveDict();

    instance.autorun(function(){
        let my slug = FlowRouter.getParam('myslug');

        // load if no loaded yet
        if (my slug && !instance.state.get("singleSchool")) {
            Meteor.call("getSingleSchool", mySlug, function(err, res){
                //handle err if occurred...
                this.state.set("singleSchool", res);
            }.bind(instance)); //make instance available
        } 

    });
});

如果加载了学校,则助手然后只返回一个值:

singleSchool: function () {
   return Template.instance().state.get("singleSchool");   
},
于 2017-09-26T13:03:10.200 回答