sql >> Base de Datos >  >> NoSQL >> MongoDB

Mongoose validar clave externa (ref)

Seguí buscando en Google durante la última hora y vi algo sobre el alcance que me hizo pensar. El siguiente código solucionó mi problema.

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

Aunque esta fue una solución rápida, de ninguna manera fue una solución obvia (al menos para mí). El problema era el alcance de las variables.