流星:检查是否定义了集合

Meteor: Check if collection is defined

本文关键字:集合 定义 是否 检查 流星      更新时间:2023-09-26

有一个复杂的方法函数,它从不同的集合中获取一些数据。这些集合在某些(可选)包中定义。现在我需要检查集合是否已定义 - 这意味着包已添加到项目中。

我尝试使用if,但这不起作用。我仍然收到错误Articles is not defined并且脚本中止。

Meteor.methods({
    data: function () {
        if (Articles) {
            Articles.find(
                { parent: null }, 
                { fields: { title: true } } 
            );
        }
    }
});

几种方法可以执行此操作,具体取决于集合的定义方式。假设它是一个全局变量,你应该能够像这样安全地测试它:

var root = Meteor.isClient ? window : global;
if (root.Articles) {...}

另请参阅按引用列出的集合。

使用 typeof 检查它是否undefined

'use strict'; // Just to make sure we would get a reference error
if (typeof Articles === 'undefined') {
  document.querySelector('pre').innerText = 'No articles here';
}
<pre>Articles?</pre>