当“文档”保存到数据库中时,猫鼬有什么办法访问其他模式字段并更新这些文件?

时间:2020-07-08 12:24:24

标签: mongodb mongoose

我目前正在使用图书馆管理系统,并且我将MongoDB用作数据库,所以在那里我有4种模式

  1. 用户2)书3)评论4)bookIssue(处理所有书) 发行)

在这里我只提及我的User和Book Issue模式,因为我只需要有关这两种模式的帮助,

bookIssueHistory: { type: Array, default: null, }

每当通过“ bookIssue”模式发行一本书时,我要将那本书的“ id”存储到我的“ userSchema”中的“ bookIssueHistory”数组(如上所述)中,因此我已经提到了这两种模式下方:

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'Please enter your name'],
  },
  email: {
    type: String,
    required: [true, 'Please enter your email'],
    unique: true,
    lowercase: true,
    validate: [validator.isEmail, 'Please enter a valid email'],
  },
  photo: String,
  role: {
    type: String,
    enum: ['user', 'admin'],
    default: 'user',
  },
  password: {
    type: String,
    required: [true, 'Please enter your password'],
    minlength: 8,
    select: false,
  },
  passwordConfirm: {
    type: String,
    required: [true, 'Re-Enter your password'],
    validate: {
      validator: function (el) {
        return el === this.password;
      },
      message: 'Entered password and confirmed password do not match',
    },
  },
  passwordChangedAt: Date,
  passwordResetToken: String,
  passwordResetExpires: Date,

  noOfBooksIssued: {
    type: Number,
    default: 0,
  },

  currentlyIssuedBooks: {
    type: Number,
    max: [3, 'You are only allowed to issue 3 books at a time'],
    default: 0,
  },

  bookIssueHistory: {
    type: Array,
    default: null,
  },

  active: {
    type: Boolean,
    default: true,
    select: false,
  },
});

我的图书发行模式如下:

const bookIssueSchema = mongoose.Schema({
  issuedAt: {
    type: Date,
    default: Date.now,
  },
  totalIssues: {
    type: Number,
    default: 0,
  },
  book: {
    type: mongoose.Schema.ObjectId,
    ref: 'Book',
    required: [true, 'issue must belong to a book.'],
  },
  user: {
    type: mongoose.Schema.ObjectId,
    ref: 'User',
    required: [true, 'issue must belong to a user.'],
  },
});

   

    

1 个答案:

答案 0 :(得分:0)

您可以使用猫鼬middleware,特别是在将bookIssue插入数据库之前,使用预保存钩子来运行一些逻辑。

bookIssueSchema.pre('save', function () {
  // you can access the current document to be saved by `this`
  if (this.isNew) { // apply to new bookIssue only
    await this.model('User').findByIdAndUpdate(this.user, {
      $addToSet: { bookIssueHistory: this.book } // use $addToSet to ensure distinct values, otherwise use $push
    })
  }
})

重要提示:仅当您使用BookIssue.create()bookIssue.save()时,才会运行预保存钩子,而在运行BookIssue.insertMany()时,则不会运行