I have tried several different ways to validate a foreign key in Mongoose and cannot figure it out.
I have a schema like this:
//Doctors.js
var schema =
I kept googling over the past hour, and saw something about scope that got me thinking. The following code fixed my problem.
//Doctors.js
var mongoose = require('mongoose');
var schema = mongoose.Schema({
email: { type: String }
}
module.exports = mongoose.model('Doctors', schema);
//Patients.js
//var Doctors = require('./Doctors'); --> delete this line
var mongoose = require('mongoose');
var schema = mongoose.Schema({
email: { type: String },
doctor: { type: String, ref: 'Doctors' }
}
schema.pre('save', function (next, req) {
var Doctors = mongoose.model('Doctors'); //--> add this line
Doctors.findOne({email:req.body.email}, function (err, found) {
if (found) return next();
else return next(new Error({error:"not found"}));
});
});
module.exports = mongoose.model('Patients', schema);
Although this was a quick fix, in no way was it an obvious fix (at least to me). The issue was the scope of variables.