【问题标题】:How to filter through model?如何通过模型过滤?
【发布时间】:2015-10-06 14:51:41
【问题描述】:

假设 StrongLoop (https://docs.strongloop.com/display/public/LB/HasManyThrough+relations) 使用的医生和患者的标准示例:

common/models/physician.json

{
  "name": "Physician",
  "base": "PersistedModel",
  "properties": {
    "name": {
      "type": "string"
    }
  },
  "validations": [],
  "relations": {
    "patients": {
      "type": "hasMany",
      "model": "Patient",
      "foreignKey": "patientId",
      "through": "Appointment"
    },

common/models/patient.json

{  
  "name": "Patient",
  "base": "PersistedModel",
  "properties": {
    "name": {
      "type": "string"
    }
  },
  "validations": [],
  "relations": {
    "physicans": {
      "type": "hasMany",
      "model": "Physician",
      "foreignKey": "physicianId",
      "through": "Appointment"
    },

common/models/appointment.json

{  
  "name": "Appointment",
  "base": "PersistedModel",
  "properties": {
    "appointmentDate": {
      "type": "date"
    }
  },
  "validations": [],
  "relations": {
    "physician": {
      "type": "belongsTo",
      "model": "Physician",
      "foreignKey": "physicianId"
    },
    "patient": {
      "type": "belongsTo",
      "model": "Patient",
      "foreignKey": "patientId"
    },

如何通过约会日期从医生筛选中获取患者?

我尝试使用这样的东西:

Physician.findOne({
    "where": {"id": physId},
    "include": {
        "relation": "patients",
        "scope": {
            "where": {
                "appointmentDate": { "gt": fixedDate }
            }
        }
    }
}, callback);

但似乎 Loopback 在 Patient 模型上而不是在 Appointment 模型上寻找约会日期。

一些有用的提示? 谢谢!

【问题讨论】:

  • 你应该看看 mongoose :) mongoosejs.com 还要注意 MongoDB 内部的关系并不理想,所以你可能需要重新考虑你的数据库模型 :)

标签: mongodb filter has-many-through loopbackjs strongloop


【解决方案1】:

我认为您对 mongo 查询的理解可能有问题。

mongo中的操作符必须在'$'开头,所以你的gt应该改成$gtwhere应该改成$哪里

要通过约会日期从医生过滤中获取患者,我们可以分两步完成,假设您有特定医生的 id(physId)。

var appointments = Appointment.find({
  "relation.physician.foreignKey": physId,
  "properties.appointmentDate": { $gt: fixedDate }
});  // get all appointments after fixedDate
var patients = [];
appointments.forEach(function(appoint) {
  patients.push(appoint.relation.patient);
})

return patient;  // all patients in appointments

在节点 API 中 我已经阅读了文档中的 find 方法,它使用 where 过滤器来匹配特定字段的值,但我认为它与原点相似 :-)

Appointment.find({
  "relation.physician.foreignKey": physId,
  "properties.appointmentDate": { gt: fixedDate }
})

然后你可以使用像 _.forEach(underscore.js) 这样的方法从结果中获取患者

希望它能解决你的问题;

【讨论】:

  • 关于$,它不在loopback定义中。 (docs.strongloop.com/display/public/LB/Where+filter)。
  • 嗯,我觉得是API,query和operators和原来的mongo有些小区别,但是query是差不多的
  • 您的解决方案在 Loopback 中似乎无法正常工作。无论如何,我以类似的方式进行管理......我查找了具有特定日期的所有约会,然后寻找与该约会相关的医生。还是谢谢!
  • 问题不是mongo,而是loopback,mongo只是使用的连接器。连接器可能会带来限制,但所有连接器的 API 都是相同的。我有同样的问题,“通过模型”记录了其他字段,但不是过滤这些字段的方式。目前看来是不可能了。
猜你喜欢
  • 2021-12-29
  • 2017-12-21
  • 1970-01-01
  • 2011-03-20
  • 2019-12-04
  • 1970-01-01
  • 2013-06-26
  • 1970-01-01
  • 2016-08-05
相关资源
最近更新 更多