Javascript Meteor.js集合在客户端上为空
为什么Javascript Meteor.js集合在客户端上为空,javascript,node.js,mongodb,meteor,Javascript,Node.js,Mongodb,Meteor,为什么myCollection.find().fetch()返回一个空数组[],即使调用是在if(data){…}中进行的?if语句是否确保在执行console.log()之前已检索到集合 这将在浏览器Javascript控制台中返回[]。确实如此,但在Javascript中,您有以下奇怪的行为 if ([]){ console.log('Oops it goes inside the if') } // and it will output this, nontheless it is c
myCollection.find().fetch()
返回一个空数组[]
,即使调用是在if(data){…}
中进行的?if
语句是否确保在执行console.log()
之前已检索到集合
这将在浏览器Javascript控制台中返回
[]
。确实如此,但在Javascript中,您有以下奇怪的行为
if ([]){
console.log('Oops it goes inside the if')
} // and it will output this, nontheless it is counter-intuitive
这是因为JS引擎将Boolean([])
强制转换为true
。你可以知道不同的类型有多不同
检查数组开头是否为空
a = [];
if (a.length){
//do your thing
}
您可以使用count()
,它返回结果的数量<代码>数据本身将是一个空数组,[]
这不是假的([]==true
)
也不要使用fetch()。如果需要,可以使用.forEach
循环浏览它
var data = myCollection.find();
if(data.count())
console.log(data);
//If you need it for something/Not sure if this is right but just an example
$('#chart').render(data.fetch())
问题是您必须等待来自服务器的数据。当您只使用Template.name.rendered
函数时,它会立即被调用。您必须使用Template.name.helpers
函数等待来自服务器的数据。所有内容都在中描述。当您“删除自动发布”时,似乎还必须在客户端上订阅
if(Meteor.isClient) {
Meteor.startup(function() {
Myvars = new Mongo.Collection("myvars");
Meteor.subscribe('myvars')
});
}
并在服务器上启用允许和发布
if(Meteor.isServer) {
Meteor.startup(function () {
Myvars = new Mongo.Collection("myvars");
Myvars.allow({
insert: function () {
return true;
},
update: function () {
return true;
},
remove: function () {
return true;
}
});
if (Myvars.find().count() == 0) {
Myvars.insert({myvalue:'annoyed'});
}
Meteor.publish("myvars", function() {
return Myvars.find();
});
});
}
我也是新手。我只是希望拥有一个所有客户都能分享的全球价值。从初学者的角度来看,这似乎是一个有用的想法,是对流星团队的一个完全的监督,但没有以这种方式清楚地记录下来。我也不知道什么是允许获取,这在官方文档中也完全不清楚。问题是,为什么Meteor会返回空的集合。我想你没有以正确的方式发布它,或者根本没有这样做。发布代码后,我们将能够提供帮助。@Jagiauto publish
尚未删除,执行console.log(myCollection.find().count())
在浏览器Javascript控制台中返回一个正数。执行模板帮助程序代码时,数据
似乎是[]
,导致收集数据丢失。但是,当在Javascript控制台中执行console.log(myCollection.find().count()
时,它确实会显示为查询检索到的所有文档的计数。谢谢,建议代码中的data.count()
在执行data.count()时返回0
)浏览器Javascript控制台中的
返回正确的计数。因此收集数据仍然无法获取。在模板中使用除
渲染
以外的其他方法。chart.rendered似乎可以避免此问题,为什么会这样?发生这种情况是因为代码运行得太早。meteor最初加载时,中没有数据它来得晚一点(大约一秒钟后)。您必须将其与订阅功能绑定,以便在呈现模板且数据可用后触发,或者如果您知道自己的操作正确,则使用Deps.autorun
page@Akshat你能提出一个正确的模式来做第一种方法吗?我的情况是,我需要扩展co的一些对象L操作(随机),将它们标记为carrousel的活动。有时,由于find().fetch(),extends会收到一个空列表。我明白你的意思。请稍等。:)将链接留给其他被隔开的外星人,你可以忽略==0
if(Meteor.isServer) {
Meteor.startup(function () {
Myvars = new Mongo.Collection("myvars");
Myvars.allow({
insert: function () {
return true;
},
update: function () {
return true;
},
remove: function () {
return true;
}
});
if (Myvars.find().count() == 0) {
Myvars.insert({myvalue:'annoyed'});
}
Meteor.publish("myvars", function() {
return Myvars.find();
});
});
}