【问题标题】:Mongoose pre save middleware error is empty objectMongoose 预保存中间件错误是空对象
【发布时间】: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 Docsthis answer 的解决方案,但没有任何效果。

请告诉我它背后的原因以及我应该如何解决它。谢谢。

【问题讨论】:

    标签: node.js mongodb mongoose middleware mongoose-schema


    【解决方案1】:

    将您尝试传递的虚假 ID 投射到 mongoose.Schema.ObjectId(*YOUR_STRING_ID*) 或者干脆让猫鼬新建一个const id = new mongoose.Schema.ObjectId()

    【讨论】:

    • 也许您可以向我们提供您遇到的错误,以便我们更好地了解您的问题。过去我在伪造 ObjectIds 来模拟多个场景时遇到了一些问题,并且成功了
    猜你喜欢
    • 1970-01-01
    • 2021-05-29
    • 2020-04-22
    • 1970-01-01
    • 2019-09-11
    • 2020-11-15
    • 2020-10-17
    • 1970-01-01
    • 2017-06-26
    相关资源
    最近更新 更多