Mongoose Validate Foreign Key (ref)

前端 未结 1 1583
执念已碎
执念已碎 2021-01-27 09:25

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 =          


        
相关标签:
1条回答
  • 2021-01-27 09:30

    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.

    0 讨论(0)
提交回复
热议问题