NelieluTu NelieluTu - 29 days ago 8
JSON Question

.populate() issue with references

var mongoose = require('mongoose')
mongoose.connect('mongodb://127.0.0.1/DocTest');

var patientsSchema = mongoose.Schema({
//This is the value I wanna populate in the rdvs collection.

ssn: String
//But I can't see to have it working.

});


var patients = mongoose.model('patients', patientsSchema);

var Max = new patients({
ssn: "okokok"
});
Max.save(function (err) {
if (err) {
console.log(err);
}
else {
console.log('wink')
}
});

var rdvsSchema = mongoose.Schema({
Heure: {
type: Date
},
patient: {
type: mongoose.Schema.Types.ObjectId, ref: 'patients'
}
});

var rdvs = mongoose.model('rdvs', rdvsSchema);

var rdvs1 = new rdvs({
Heure: 14
}
);
rdvs1.save(function (err) {
if (err) {
console.log(err);
}
else {
console.log('wonk')
}
});


This is the request I'm trying to have working :

rdvs.findOne().populate('patient').exec(function(err, rdvs){
console.log (rdvs.patient.ssn)
});


I'm struggling here, the issue here is I wanna add ssn's value from patients to my rdvs collection.

Answer Source

Mongoose operations are asynchronous. You need to wait for the operation is done before doing other things. In your case, the second query depends on the response of your first query -- therefore you need to nest your operations.

// setup schemas
var patientSchema = mongoose.Schema({
    ssn: String
});

var rdvSchema = mongoose.Schema({
    Heure: Number, // changed: you're expecting a number
    patient: { type: mongoose.Schema.Types.ObjectId, ref: 'Patient' }
});

var Patient = mongoose.model('Patient', patientSchema);
var Rdv = mongoose.model('Rdv', rdvSchema);

// create a new patient
Patient.create({ ssn: "okokok" }, function (err, patient) {
    if (err) {
        console.log(err);
        return;
    }
    if (!patient) {
        console.log('patient could not be created');
        return;
    }
    // you can only create a RDV once a patient has been created
    Rdv.create({ Heure: 14, patient: patient._id }, function (err, rdv) {
        if (err) {
            console.log(err);
            return;
        }
        if (!rdv) {
            console.log('rdv could not be created');
            return;
        }
        // send response
    });
});

Aside: get into the habit of naming your variables properly. Usually, models are singular and capitalized e.g. Patient and documents are lowercase e.g. patient.