Search code examples
javascriptmongodbmongoosemongoose-populatedatabase

Trying to associate two children collections to a parent collection using populate


'Im trying to have an array of patients Objectids and an array of data(information about doctor) objectids inside the doctors collection. This is the beginning of the code then I got lost. I think I want to use something like this Doctor.find().populate('patients data'). Then if someone could show me how to access the information that would be great.

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");
})

Solution

  • To access the information, the app should be able to receive requests; a 'get' method needs to be defined on the app object:

    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);
        });
    });