Trouble publishing/subscribing to a Mongo aggregate query

£可爱£侵袭症+ 提交于 2019-12-08 13:23:08

问题


Using Meteor and Iron-Router, I'm trying to publish the following mongo query (in the server folder):

Meteor.publish("getTestList", function() {
  return Tests.aggregate(
    [{
      $project : {
        "name" : 1,
        "description" : 1,
        "testNumber" : 1
      }
    }, {
      $sort : {
        "testNumber" : 1
      }
    }
  ])
});

Note that I have tested this query in the meteor mongo console tool and it works fine there. Also Tests is

Tests = new Mongo.Collection("tests")

and I am subscribing in the router like this:

Router.route('/user', {

  waitOn: function() {
    // return [Meteor.subscribe("tests")];
    return [Meteor.subscribe("tests"),Meteor.subscribe("getTestList")];
  },

  action: function() {
    if (!this.ready()) {
      this.render('loading');
    }
    else {
      Session.set("testName", "blablabla")
      Session.set("submitted", false)
      this.layout('BasicLayout')
      this.render('UserPortal')
    }
  }
});

And if I navigate to /user then it never gets passed the loading...screen. There are no errors in the console, and if I subscribe only to tests and not to getTestList (i.e. the commented out line in the code), then the UserPortal template does load but I get a console error stating the Tests.aggregate does not exist.

What have I done wrong?


回答1:


Meteor does not support aggregation yet. You can get it to work this way though:

Add in an aggregation package: meteor add meteorhacks:aggregate

Use Meteor.call/Meteor.methods instead, since a aggregation result is static at this point. No reactivity supported.

server side

Meteor.methods({
    "getTestList" : function() {
        return Tests.aggregate(
        [{
            $project : {
            "name" : 1,
            "description" : 1,
            "testNumber" : 1
          }
        }, {
          $sort : {
            "testNumber" : 1
          }
        }
      ])
    }
});

Client side:

Your template

Template.xx.onCreated(function() {

    Meteor.call("getTestList", function(err, result) {
        Session.set("testlist", result);
    });
});

Then you can access the data 'reactively' (when its ready) by checking out Session.get("testlist");



来源:https://stackoverflow.com/questions/30278327/trouble-publishing-subscribing-to-a-mongo-aggregate-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!