【问题标题】:creating a reference document schema for mongoose and node.js为 mongoose 和 node.js 创建参考文档模式
【发布时间】:2016-11-16 19:07:58
【问题描述】:

嗨,我是 mongodb 的新手,我正在学习它并为我的一个使用 node.js 的爱好项目实施,请帮我一个模式和查询来完成以下项目。

我有一家医院,每位患者的详细信息都会在他第一次就诊时进行登记,每次就诊时,我都需要通过参考为该患者添加一次就诊。

var patientschema=mongoose.schema(
                   {
                      objectid:"12345678"
                      patientname: string,
                      patientDOB:Date,
                      Gender:string,
                      registrationfee:number,
                      visits:[{objectid:1234},{objectid:5678}]
                   });

访问模式就像

var visitschema = mongoose.schema({
                                   objectid:"1234",
                                   patientid:"12345678"
                                   visitdate:date,
                                   reason:string,
                                   consultingdoctor:string
                                   consultingfee:number                      
                                  }); 

请为我提供适当的架构和查询,以便从 node.js 应用程序实现此目的。

【问题讨论】:

  • 您没有在参考文献中写入实际值。您需要传递 ref 字段。检查此链接。 mongoosejs.com/docs/populate.html
  • 是否创建了任何示例或示例应用程序?

标签: node.js mongodb


【解决方案1】:

在您的情况下,这两个架构应该如下所示。

var patientschema=mongoose.schema(
{
  patientname: string,
  patientDOB:Date,
  Gender:string,
  registrationfee:number,
  visits:[{ type: mongoose.Schema.Types.ObjectId, ref: 'Visit' }]
});

var visitschema = mongoose.schema(
{
   patientid:{ type: mongoose.Schema.Types.ObjectId, ref: 'Patient' }
   visitdate:date,
   reason:string,
   consultingdoctor:string
   consultingfee:number                      
}); 

var Visit  = mongoose.model('Visit', visitschema);
var Patient = mongoose.model('Patient', patientschema);

现在让我们创建新的患者条目:

var p1 = new Patient({name: 'Some Name', patientDOB : '2016-11-11', Gender : 'male', registrationfee : 123});

现在您可以为该患者添加就诊次数。

var v1 = new Visit({patientid : p1._id, ... Fill Other Fields here });

现在保存此访问时,它会变得有趣

v1.save(function(err, res){

});

Mongoose 会在内部将 v1 的 ID 附加到您的患者就诊数组中。您可以稍后搜索它们。

Patient.find().populate('visits').exec(function(err, res){
    // Here the P1 with have array of Visits
});

【讨论】:

    猜你喜欢
    • 2016-06-12
    • 1970-01-01
    • 2017-06-22
    • 2014-05-13
    • 2013-06-29
    • 1970-01-01
    • 2021-06-21
    • 2018-03-30
    • 1970-01-01
    相关资源
    最近更新 更多