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

Meteor.js Collection empty on Client

本文关键字:集合 js Meteor 客户端      更新时间:2023-10-19

为什么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本身将是一个空数组,[]不是伪数组([] == 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();
      });
    });
  }

我也是新手。我只是想拥有所有客户都能分享的全球价值。从初学者的角度来看,这似乎是一个有用的想法,也是对流星团队的完全监督,但没有以这种方式明确记录。我仍然不知道什么是允许获取,这在官方文件中也完全不清楚。

确实如此,但在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
}