我正在尝试使用通过Meteor客户端订阅获得的MongoDB集合。除此之外,在服务器端,必须从远程服务器获取已发布的集合。该代码改编自标准的Meteor示例之一。这是服务器代码:
import { Meteor } from 'meteor/meteor';
Meteor.startup(() => {
var sconn= new MongoInternals.RemoteCollectionDriver("mongodb://user:passwd@192.168.155.116:27017/mydb");
export const STasks= new Mongo.Collection("myCollection",{_driver: sconn});
Meteor.publish('stasks', function stasksPublication() {
return STasks.find({});
});
});
而且,在客户端,我有
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import './main.html';
// >>>>> I suppose these two functions are irrelevant for the problem at hand,
// >>>>> but I left just for sake of completeness.
Template.hello.onCreated(function helloOnCreated() {
// counter starts at 0
this.counter = new ReactiveVar(0);
});
Template.hello.helpers({
counter() {
return Template.instance().counter.get();
},
});
// >>>>> Here is where the problem happens:
Template.hello.events({
'click button'(event, instance) {
// increment the counter when button is clicked
instance.counter.set(instance.counter.get() + 1);
// My code to access data:
var STasks=new Mongo.Collection("myCollection");
Meteor.subscribe('stasks');
console.log('Testing data');
console.log(STasks.find().fetch());
},
});
但我在客户端控制台上获得的只是一个空的'[]'。我验证了在服务器上访问myCollection中的文档没有问题。
答案 0 :(得分:0)
试试这个:
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import './main.html';
var STasks=new Mongo.Collection("myCollection");
Template.hello.onCreated(function helloOnCreated() {
// ...
this.subscribe('stasks');
});
Template.hello.helpers({
// ...
});
Template.hello.events({
'click button'(event, instance) {
// ...
console.log(STasks.find().fetch());
},
});
答案 1 :(得分:0)
我找到了解决方案:在发布方面,使用limit
函数的find
参数。
Meteor.publish('stasks', function stasksPublication() {
return STasks.find({},{limit:5});
});
看起来很奇特,但我对此有一个解释:myCollection
非常庞大,大约有500K行。结果行为显示为空括号,而不是引发错误。