我不明白为什么schema.method.log和schema.pre('save')无法正常工作。
感谢您的帮助!
// plugin.js
const LogSchema = require('../models/log')
const plugin = function (schema) {
schema.post('init', doc => {
console.log(doc)
})
schema.pre('save', function(next) {
console.log('save') // <---------- this method is not executed!
next()
})
schema.methods.log = function(data) {
return LogSchema.create(data)
}
}
module.exports = plugin
// products.js
const express = require('express')
const router = express.Router()
const Products = mongoose.model('products')
router.post('/', async (req, res) => { // <--- POST method
const product = new Products({
name: req.body.name,
})
console.log(typeof product.log) // <---------- `UNDEFINED !`
await product.save() // <--- product save correctly
res.json({
status: 'Product Saved'
})
})
// index.js
[...]
mongoose.plugin(require('./server/middlewares/plugin.js')) // <----- Works well
[...]
我对MongoDB还是很陌生,在花了几个小时的时间仔细检查了代码之后,我才明白为什么事情会出错。