【问题标题】:Mongodb embedded objects and Meteor collection helpersMongodb 嵌入对象和 Meteor 收集助手
【发布时间】:2016-10-17 08:10:14
【问题描述】:

我正在从事一个 Meteor 项目,我有一些 Mongo 集合,但我不确定如何处理关系和 Meteor 集合帮助程序包。

到目前为止,我们一直在存储嵌入式文档,例如,我们有一个 Internship 集合,每个实习都有一个嵌入文档,其中包含创建此实习的用户(所有者)。

我们决定使用 Meteor 收集助手包 (https://github.com/dburles/meteor-collection-helpers),因此我们可以添加返回所需值的方法。问题是嵌入式文档丢失了它们给定的方法。

在实习中,我们只存储相关的集合 id,如果我们想获得分为 3 个不同属性街道、邮政编码和城市的 Internship.address,我们只需调用 'internship.getAddress( )'。另一个例子是,如果您正在处理申请文件,则获取实习地址。您可以调用方法 Application.getInternship().getAddress()。通过这样做,我们不必存储嵌入的文档。

当我们需要使用不同的字段进行 Mongo 查询时,就会出现问题。我们有一个非常简单的搜索函数,它返回与给定字符串匹配的所有文档:

Application.search = (query) => {
    Application.find({
        'applicant._id': Meteor.userId(),
        $or: [
          {"internship.title": { $regex: query, $options: 'i' }},
          {"internship.description": {$regex: query, $options: 'i' }},
        ],
    }, {sort: { updatedAt: -1 },
    }).fetch();
}

Internship.title 和描述不再存储在实习嵌入文档中,所以我们想知道如何处理这个问题。

【问题讨论】:

    标签: mongodb meteor


    【解决方案1】:

    假设您的Applications 集合通过Applications 集合中internshipIds数组 与您的Internships 集合相关。然后您可以执行以下操作:

    Application.search = (query) => {
      // find cursor internships that match the query
      const matchingInternships = Internships.find({
        $or: [
          {title: { $regex: query, $options: 'i' }},
          {description: {$regex: query, $options: 'i' }}
        ]
      });
      // extract the list of _ids from this cursor
      const intershipIds = matchingInternships.map(i=>{return i._id}); // array of internshipIds
      Application.find({
        'applicant._id': Meteor.userId(),
        internshipId: {$elemMatch: internshipIds } // look for internshipIds that are in the array
        },{sort: { updatedAt: -1 },
      }).fetch();
    }
    

    这有点类似于执行嵌套的 SQL SELECT 语句,例如:

    SELECT * FROM APPLICATIONS WHERE internshipID IN
      (SELECT ID FROM INTERNSHIPS WHERE
        (title LIKE query OR description LIKE query)
      );
    

    【讨论】:

      猜你喜欢
      • 2016-01-31
      • 1970-01-01
      • 2015-12-01
      • 1970-01-01
      • 2015-08-13
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      相关资源
      最近更新 更多