尝试使用populate将两个子集合关联到父集合

时间:2016-01-26 00:12:01

标签: javascript mongodb mongoose mongoose-populate database

'我试图让一系列患者Objectids和一系列数据(有关医生的信息)目标在医生集合中。这是代码的开始然后我迷路了。我想我想使用像Doctor.find().populate('patients data')这样的东西。然后,如果有人可以告诉我如何访问那些很棒的信息。

var express = require("express");
var app = express();
var mongoose = require("mongoose");

mongoose.connect("mongodb://localhost/population")

        var doctorSchema = new mongoose.Schema({
            name : String,
            patients : [{type : mongoose.Schema.Types.ObjectId, ref : "Patient"}],
            data : [{type : mongoose.Schema.Types.ObjectId, ref : "Data"}]
        })

        var patientSchema = new mongoose.Schema({
            name : String
        })
        var dataSchema = new mongoose.Schema({
            income : String
        })

        var Doctor = mongoose.model("Doctor",doctorSchema );
        var Patient = mongoose.model("Patient", patientSchema);
        var Data = mongoose.model("Data", dataSchema);

        var doc1 = new Doctor({"name" : "doc1"})
        doc1.save(doc1, function(err, doc){
            if(err){ 
                console.log(err)
            }else{
                console.log("saved")
            }

        })



app.listen(3000, function(){
    console.log("listening on 3000");
})

1 个答案:

答案 0 :(得分:0)

要访问该信息,app应该能够接收请求; a' get'需要在app对象上定义方法:

app.get('/:id', function(req, res) {
  var doctorID = req.params.id;

  Doctor
    .findOne({_id: doctorID})
    .populate('patients data')
    .exec(function(err, doctor) {
      if (err) throw err;
      res.send(doctor);
    });
});