【发布时间】:2020-09-07 16:41:38
【问题描述】:
我有一个 Fee 架构来保存费用支付详细信息,其中有一个 student 属性是对 Student 架构的引用,它告诉谁支付了费用。
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Student = require('./student');
const fee = new Schema({
student: { // Student ID
type: Schema.Types.ObjectId,
ref: 'Student'
},
paidFor: {
type: Date
},
paidOn: {
type: Date,
default: Date.now
},
due: Number,
fine: Number,
late: Number,
misc: Number,
tution: Number,
library: Number,
admission: Number,
development: Number,
electricity: Number,
examination: Number
});
// This pre save middleware to check if the Student ID belongs to some student or not.
fee.pre('save', function(next) {
const { student } = this;
Student.findOne({ _id: student }, (error, result) => {
if (error) {
return next(new Error(error));
}
if (!result) { // If student not found.
return next(new Error("Student not found."));
}
return next();
});
});
module.exports = new mongoose.model("Fee", fee);
问题在于pre('save')... 中间件。当我为它提供一个有效的student id 时,它属于Student 集合中的某个文档,它在通过pre('save')... 中间件后成功保存它,正如预期的那样。
但是当我给它一个不属于Student 集合中任何文档的student id 时,它不会按我的意愿保存它,但它会将空对象作为错误。错误对象没有像我上面传递的"Student not found." 这样的任何消息。
我尝试了Mongoose Docs 和this answer 的解决方案,但没有任何效果。
请告诉我它背后的原因以及我应该如何解决它。谢谢。
【问题讨论】:
标签: node.js mongodb mongoose middleware mongoose-schema