【问题标题】:schema .pre('save') does not triggerschema .pre('save') 不会触发
【发布时间】:2021-05-31 06:29:21
【问题描述】:

您好,我打算在触发 pre 方法后打印出pre,但它不起作用。

import mongoose from'mongoose'
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log('connected')
});

// test for pre hooks
const toySchema = mongoose.Schema({ name: String, created: Date });
const Toy = mongoose.model('Toy', toySchema)

toySchema.pre('save', function(next) {
  if (!this.created) this.created = new Date;
  console.log('pre');
  next(new Error('something went wrong'));
});

const firstoy = new Toy({ name: 'tank' })
firstoy.save(function (err, firstoy) {
  if (err) return console.error(err);
});

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    找到书面答案:在编译模型之前定义中间件

    https://mongoosejs.com/docs/middleware.html#defining

    【讨论】:

      猜你喜欢
      • 2015-07-20
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      • 2016-04-29
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 2022-10-23
      相关资源
      最近更新 更多