猫鼬验证外键(参考) [英] Mongoose Validate Foreign Key (ref)
本文介绍了猫鼬验证外键(参考)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试了几种不同的方法来验证Mongoose中的外键,但无法弄清楚.
I have tried several different ways to validate a foreign key in Mongoose and cannot figure it out.
我有一个这样的架构:
//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'
有人知道如何做与我在这里试图做的事情类似的事情吗?
Anyone know how to do something similar to what I am trying to do here?
推荐答案
在过去的一个小时里,我一直在使用Google进行搜索,并发现了一些有关范围的知识,这让我开始思考.以下代码解决了我的问题.
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.
这篇关于猫鼬验证外键(参考)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文