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')
}
});
这是我正在尝试工作的请求:
rdvs.findOne().populate('patient').exec(function(err, rdvs){
console.log (rdvs.patient.ssn)
});
我在这里苦苦挣扎,这里的问题是我想将患者的ssn值添加到我的rdvs集合中。
答案 0 :(得分:1)
Mongoose操作是asynchronous。在执行其他操作之前,您需要等待操作完成。在您的情况下,第二个查询取决于您的第一个查询的响应 - 因此您需要嵌套您的操作。
// 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
});
});
除此之外:养成正确命名变量的习惯。通常,models是单数且大写的,例如Patient
和documents是小写的,例如patient
。