【问题标题】:Mongoose Validate Foreign Key (ref)Mongoose 验证外键(参考)
【发布时间】:2019-01-15 21:14:15
【问题描述】:

我尝试了几种不同的方法来验证 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'

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

【问题讨论】:

  • 所以,我可以使用 mongoose 4.0.5 和 mongo 2.4.6 让它在我的机器上运行。当您console.log(Doctors) 时,您会得到什么?
  • 我收到{}。但我刚刚找到答案,给我一秒钟发布它

标签: node.js mongodb mongoose


【解决方案1】:

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

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

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

【讨论】:

  • 嗨,杰里米,我有一个关于您如何分配外键的问题,所以我们可以参考我所指的任何键,因为我看到大多数人使用 {type: Schema.Types.ObjectId,ref :"some collection"} 你的方法能正常工作吗?
猜你喜欢
  • 2022-01-24
  • 2018-06-28
  • 2017-01-13
  • 2014-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-20
  • 1970-01-01
相关资源
最近更新 更多