所以我有两个模型:
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);
收入.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;
现在我定义了事务的预保存挂钩,但是当我调用
收入。创建()
,这个钩子永远不会被调用,我只是得到了一个错误:
需要用户数量
(我想在预存中设置)。