猫鼬鉴别器未调用父级预保存钩子

时间:2018-08-18 19:11:30

标签: node.js mongodb mongoose

所以我有2个模型:

Transaction.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { User } = require('./index');

const TransactionSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    amount: {
        type: Number,
        required: true
    },
    userAmount: {
        type: Number,
        required: true
    }

}, { discriminatorKey: 'kind' });

TransactionSchema.pre('save', async function () {
    console.log('entered here?');
    const user = await User.findById(this.user);
    const modifier = this.kind == 'INCOME' ? 1 : -1;
    const amount = user.balance + (modifier * this.amount);
    this.userAmount = amount;
    user.balance = amount;
    await user.save();
});

module.exports = mongoose.model('Transaction', TransactionSchema);

Income.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Transaction = require('./Transaction');

const Income = Transaction.discriminator('INCOME', new Schema({
    client: {
        type: Schema.Types.ObjectId,
        ref: 'Client'
    }
}))

module.exports = Income;

如您所见,收入是交易的判别符。 现在,我在Transaction上定义了预保存钩子,但是当我调用 Income.create() 时,该钩子从未被调用,而我得到的错误是: userAmount是必需的(我想在预保存中设置)。

0 个答案:

没有答案