使用 Meteor 和 MongoDB 根据 ID 数组查找用户

Find users based on array of IDs using Meteor and MongoDB

我目前在一个网页上显示来自 Meteor.users.find() 的所有用户,其中包含 {{#each user}}。但是,我想根据邮政编码限制我的搜索。

  1. 用户输入邮政编码。
  2. 查找邮政编码的城市名称。
  3. 查找该城市内的所有邮政编码。
  4. 查找在该城市具有任何邮政编码的所有用户。
  5. 列出页面上的所有用户。

    // Step 1: User input (OK)
    input_zip = '1234';
    // Step 2: Get city name for this ZIP (OK)
    var zip_place = Locations.findOne({ zipCode: input_zip })['place'];
    // Step 3: Get all zip codes in that city (OK)
    var zip_codes = Locations.find({ place: zip_place }).fetch();
    // Step 4 (I'm aware this syntax is totally wrong, but you get the idea)
    var zip_users = Meteor.users.find({ profile.zipcode: zip_codes }).fetch();
    
    // Step 5: List users on page with zip codes in that array.
    
    {{#each user in zip_users}}
      <p>bla bla</p>
    {{/each}}
    

使用数组中的值搜索用户的最有效方法是什么? 完整的代码示例将不胜感激。谢谢。

你可以使用 $in 运算符来达到这个目的。

Meteor.users.find({ 'profile.zipcode':{$in: zip_codes} }).fetch();

有关 $in 运算符的更多详细信息,请转到 mongo manual