【问题标题】:Meteor.js Loop over an array to check if value already exists in collection documentsMeteor.js 循环遍历数组以检查集合文档中是否已存在值
【发布时间】:2018-06-26 07:15:05
【问题描述】:

我找不到这个问题的答案。我看到的所有示例都是在集合上查找字段Number 的值123456。 但是我想知道是否有可能是我是否可以在整个集合文档中搜索数组中的一个数字。 例如,这是我收藏的第一个文档:

{
  "_id": "Qfjgftt7jLh3njw8X",
  "reference": 102020026, // Field that I want to check
  "type": "Moradias",
  "n_beds": 5,
  "price": 30000,
  "departement": "Portalegre",
  "city": "Ponte de Sor",
  "street_name": "Rua do Comércio, CE",
  "l_surface": 248,
  "is_exclusive": true
}

客户端正在导入一个转换为 JSON 并添加到我的集合中的 XLSX 文件,以便客户端插入 reference 数字。 然后我想遍历我的 JSON,(可能有多个引用)获取客户端导入的引用并检查这些引用是否已经存在于我的一个集合文档中。之后我会抛出一个错误。 我知道我可以做到Collection.find({reference: '102020026'}),但问题是我的收藏中可能有 100 多个不同的参考。

我希望这是有道理的,并且没有在其他地方得到回答。

提前致谢!

【问题讨论】:

    标签: javascript arrays json meteor collections


    【解决方案1】:

    您可能希望使用 $in mongo 运算符 (see doc) 来按给定数组查找所有文档:

    const ids = [
      102020026,
      102021407,
      102023660,
    ];
    
    Collection.find({reference: {$in: ids}});
    

    这将返回所有文档,其中reference 匹配 ìds` 数组中给定的数字之一。

    【讨论】:

    • 非常感谢您,在发布我的问题后,我发现了一个相关问题,由于某种原因在我搜索或提出问题时没有显示给我。 Aniway,您的回答很有用,因为我不知道 $in mongo 运算符!我将用解决方案更新我的问题并将您的问题标记为答案!再次感谢!
    【解决方案2】:

    这是我的解决方案

    使用 @Jankapunkt 回答的 Mongo 运算符 $in

      let arr = [];
        for (let c = 0; c< myJSON.length; c++) {
          arr.push(myJSON[c].reference);
      }
      if(Collection.find({reference: {$in: arr}}).count() > 1) {
        alert(`Reference ${arr} already exists`);
        throw new Error('Duplicated reference');
      }
    

    如果没有 $in Mongo 运算符,只需使用 for 循环,这将导致相同的结果:

    for (let c = 0; c < myJSON.length; c++) {
     if (Collection.find({reference: myJSON[c].reference}).count > 1) {
        alert(`Reference ${arr} already exists`);
        throw new Error('Duplicated reference');
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 2017-04-17
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      相关资源
      最近更新 更多