【问题标题】:How to only run a function if a specific field in a Mongo collection contains a specific value?如果 Mongo 集合中的特定字段包含特定值,如何仅运行函数?
【发布时间】:2017-11-27 23:21:38
【问题描述】:

我将“密钥”(以及其他一些不重要的信息)作为数组字段存储在名为“storedKeys”的集合中。

这看起来像:

{
    "_id" : "Company(02fd8fba13cf51cf)",
    "infos" : {
        "companyName" : "company",
        "street" : "exampleStreet",
        "number" : "123",
        "city" : exampleCity",
        "createdAt" : ISODate("2017-06-24T13:20:09.771Z")
    },
    "key" : ["123456789"]
}

现在,我想通过调用 Meteor 方法将此“键”字段用作在其他集合中运行某些更新的权限。此外,只有在storedKeys 中正确的_id 存在的情况下才应该执行此方法。

更准确地说:如果事件处理程序放入方法调用的变量与集合storedKeys中定义的字段匹配,则执行该方法。否则,抛出错误,不执行该方法。

为此,我尝试通过提交表单调用方法,而不是尝试在服务器端方法中使用带有 find({}) 函数的 if 子句,如下所示:

客户端(触发方法)

Template.keyCollectionThing.events({
"submit form": function (e) {
e.preventDefault();
var key = "123456789";
var id = "Company(02fd8fba13cf51cf)";
Meteor.call('updateOtherCollections', key, id);
}
});

服务器(运行方法)

    Meteor.methods({
      'updateOtherCollections': function(key, id) {

    if(storedKeys.find({"key": key}) && storedKeys.find({"_id": id})) {

       Meteor.users.update(
            {'_id': this.userId
          }, {
              $push: {
                'pushedId': id
                    }
              });

      otherDB.update(
      {'_id': this.userId
      }, {
        $push: {
          'pushedId': id
        }
      }
      );

      storedKeys.update(
      {'_id': id
    }, {
      $set: {
        "key": []
      }
    });
  }} 
 });

但是,问题在于,该方法始终正确运行,即使 storedKeys 中没有键或 storedKeys 中的 _id 不存在。因此,if () 和 find({}) 没有我期望的验证。始终执行该方法并更新集合(无需钥匙即可开门)。

【问题讨论】:

    标签: javascript arrays meteor methods


    【解决方案1】:

    .find() 返回一个 cursor,它是一个 function,它始终是 truthy

    如果您希望找到单个文档,请使用.findOne()。如果您希望找到 > 0,那么您可以测试 .find(query).count()(0 为假,任何其他数字为真)

    【讨论】:

      猜你喜欢
      • 2018-09-05
      • 1970-01-01
      • 2020-07-31
      • 2023-03-14
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      相关资源
      最近更新 更多