Meteor.js集合在客户端上为空

为什么myCollection.find().fetch()即使在if(data){...}内进行调用,也会返回一个空数组[]if语句是否确保在执行console.log()之前已经检索到集合?

 Template.chart.rendered = function() { var data = myCollection.find().fetch(); if(data) { console.log(data); } $('#chart').render(); } 

这会在浏览器Javascript控制台中返回[]

你可以使用count()来返回结果的数量。 data本身将是一个空数组, []这不是falsey( [] == 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()) 

看来,当你“删除自动发布”,你还必须在客户端订阅。

  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(); }); }); } 

我也是新来的。 我只是想拥有一个所有客户都能分享的全球价值。 这似乎是一个有用的想法(从初学者的angular度来看)和对Meteor团队的全面监督,这是没有明确的文件logging。 我也不知道什么允许提取,这在官方文档中也是完全不清楚的。

它确实,但在JavaScript中,你有以下奇怪的行为

 if ([]){ console.log('Oops it goes inside the if') } // and it will output this, nontheless it is counter-intuitive 

发生这种情况是因为JS引擎将Boolean([])强制转换为true 。 你可以在这里将不同的types转换为布尔值 。

检查你的数组是否在开始时不是空的。

 a = []; if (a.length){ //do your thing } 

问题是你必须等待来自服务器的数据。 当你使用Template.name.rendered函数时,它立即被调用。 您必须使用Template.name.helpers函数来等待来自服务器的数据。 一切都在文档中描述。