Javascript 从呈现事件访问时集合是否为空?
我订阅了一个集合,但当我试图从我的Javascript 从呈现事件访问时集合是否为空?,javascript,node.js,mongodb,meteor,Javascript,Node.js,Mongodb,Meteor,我订阅了一个集合,但当我试图从我的onRendered事件访问它时,它总是以空数组的形式返回。以下是我正在使用的方法: FlightCounts = new Mongo.Collection("flightCounts"); if (Meteor.isClient) { Meteor.subscribe('flightCounts'); Template.hello.rendered = function(){ var counts = FlightCounts.find().
onRendered
事件访问它时,它总是以空数组的形式返回。以下是我正在使用的方法:
FlightCounts = new Mongo.Collection("flightCounts");
if (Meteor.isClient) {
Meteor.subscribe('flightCounts');
Template.hello.rendered = function(){
var counts = FlightCounts.find().fetch()
console.log(counts)
}
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
Meteor.publish('flightCounts', function(){
return flightCounts.find();
})
});
}
有人知道为什么我的收藏总是空的吗?关于如何填充它有什么建议吗
if (Meteor.isClient) {
Meteor.subscribe('flightCounts');
Template.hello.rendered = function() {
var template = this;
template.autorun(function () {
var counts = FlightCounts.find().fetch()
console.log(counts)
});
}
}
您的集合未填充,因为它仍在从服务器获取数据。因此,您应该将代码包装在自动运行中,以便在数据更新时重新运行
我在手机上,所以格式可能不正确。对不起
您的集合未填充,因为它仍在从服务器获取数据。因此,您应该将代码包装在自动运行中,以便在数据更新时重新运行
我在手机上,所以格式可能不正确。很抱歉。或者,您可以使用
FlowRouter的订阅
或IronRouter的waitOn
将订阅放到那里
更新令人惊讶的是,IronRouter
现在也有了订阅
选项或者,您可以使用FlowRouter
的订阅
或IronRouter
的waitOn
将订阅放到那里
更新令人惊讶的是,IronRouter
现在也有了订阅基本问题是发布函数应该引用Meteor的Mongo.Collection
名称,FlightCounts
,而不是原始的db.Collection
名称FlightCounts
:
Meteor.publish('flightCounts', function(){
return FlightCounts.find();
});
我也同意之前的回答,即您的模板应在记录数据之前检查以确保订阅已准备就绪,否则它可能尚未到达:
Template.hello.onRendered(function(){
this.autorun(() => {
let ready = Template.instance().subscriptionsReady();
if (!ready){ return; }
let counts = FlightCounts.find().fetch();
console.log(counts);
});
});
(请注意,Template.name.rendered
的较新语法是Template.name.onRendered()
)根本问题是发布函数应该引用Meteor的Mongo.Collection
名称,FlightCounts
,而不是原始的db.Collection
名称FlightCounts
:
Meteor.publish('flightCounts', function(){
return FlightCounts.find();
});
我也同意之前的回答,即您的模板应在记录数据之前检查以确保订阅已准备就绪,否则它可能尚未到达:
Template.hello.onRendered(function(){
this.autorun(() => {
let ready = Template.instance().subscriptionsReady();
if (!ready){ return; }
let counts = FlightCounts.find().fetch();
console.log(counts);
});
});
(请注意,Template.name.rendered
的较新语法是Template.name.onRendered()
)请参阅的“订阅不阻止”部分。请参阅的“订阅不阻止”部分。我注意到使用此代码记录了多次计数。这是预期的吗?我假设它只会在ready
设置为true时运行?是的,这是预期的行为,因为FlightCounts.find()是一个被动数据源,因此每次光标更改时,自动运行都会重新运行,即使subscriptionsReady()已标记为true。此外,如果正在重新呈现模板,该函数将再次运行。请注意,如果需要,您可以停止自动运行多次。我注意到此代码会记录多次计数。这是预期的吗?我假设它只会在ready
设置为true时运行?是的,这是预期的行为,因为FlightCounts.find()是一个被动数据源,因此每次光标更改时,自动运行都会重新运行,即使subscriptionsReady()已标记为true。此外,如果正在重新呈现模板,该函数将再次运行。请注意,如果需要,您可以停止自动运行以避免多次重新运行。