【问题标题】:meteor if document exists return true/false如果文档存在,则流星返回 true/false
【发布时间】:2015-08-05 05:15:28
【问题描述】:

如何确定一个文档是否存在于 Meteor 的集合中?

已编辑:新代码。

mongodb 有一个 ProductName 为 Apples 的文档 inputproduct 是“Apples”

var exists = Products.find({ProductName: inputproduct});
                    if(exists)
                    {
                        alert("it exists");
                    }else{
                        alert('doesnt exist');
                    }

我得到的只是:“它存在”,无论 inputproduct 的值如何。我已经输出了 inputproduct 是什么,它返回“Apples”没问题。不知道这里发生了什么。使用 find 或 findOne 尝试了几种方法。

【问题讨论】:

  • 你会这样做。你也订阅数据吗?
  • 感谢您在其中编辑代码!请确保正确格式化它(它有点向右旅行)。

标签: meteor


【解决方案1】:

你几乎拥有它。但是,meteor 的 collection.findOne 将返回第一个匹配的对象,如果没有找到匹配项,则返回 undefined(这是假的)。试试这个:

var exists = Products.findOne(selector, projection);
if(exists)
 {
    do something...
 }

【讨论】:

  • 您应该仍在使用 findOne。如果您要将其更改为查找,那么您应该检查: if (exists.length > 0) {alerts('it exists');}else{...}
  • @GPicazo 谢谢,第二个例子有效。超级沮丧。我发誓我之前尝试过它并没有用,但现在它可以了。奇怪。
  • @GPicazo 感谢您的编辑。我删除了我的 cmets,因为它们不再相关。
  • @Lusty - 如果这解决了您的问题,请将主题标记为已回答。
  • 但是如果您在数据到达客户端之前调用 Collection.findOne(),即使文档实际存在,它也会返回 undefined。我们如何区分undefined(由于数据尚未加载)和undefined(因为文档实际上不存在)?
猜你喜欢
  • 2014-09-29
  • 1970-01-01
  • 2021-09-11
  • 1970-01-01
  • 2018-10-22
  • 1970-01-01
  • 2020-12-23
  • 1970-01-01
相关资源
最近更新 更多