Mongoose验证外键(参考)

时间:2015-06-16 04:55:56

标签: node.js mongodb mongoose

我已经尝试了几种不同的方法来验证Mongoose中的外键,但无法弄明白。

我有这样的架构:

//Doctors.js
var schema = mongoose.Schema({
  email: { type: String }
}
module.exports = mongoose.model('Doctors', schema);

//Patients.js
var Doctors = require('./Doctors');
var schema = mongoose.Schema({
  email: { type: String },
  doctor: { type: String, ref: 'Doctors' }
}
schema.pre('save', function (next, req) {
  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);

然而我收到此错误:Uncaught TypeError: Object #<Object> has no method 'findOne'

任何人都知道如何做类似于我在这里尝试做的事情吗?

1 个答案:

答案 0 :(得分:2)

我在过去的一小时里一直在谷歌搜索,看到了一些让我思考的范围。以下代码解决了我的问题。

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

虽然这是一个快速修复,但绝不是一个明显的修复(至少对我来说)。问题是变量的范围。