In a Next.js project, I have the below Wallet schema :
const walletSchema = new Schema(
{
title: {
type: String,
required: true,
maxlength: 20,
},
user: { type: String, required: true },
transactions_count: { type: Number, required: true, default: 0 },
expenses_transactions_count: {
type: Number,
required: true,
default: 0,
},
income_transactions_count: {
type: Number,
required: true,
default: 0,
},
balance: { type: Number, required: true, default: 0 },
expenses: { type: Number, required: true, default: 0 },
income: { type: Number, required: true, default: 0 },
},
{ timestamps: true, minimize: false }
)
walletSchema.index({ user: 1, title: 1 }, { unique: true })
walletSchema.plugin(uniqueValidator, {
message: "{PATH} {VALUE} already exists.",
})
New doc is created by passing only the 2 non-defaulted values :
const wallet = new WalletModel({ title, user })
await wallet.save()
And the below Transaction schema :
const transactionSchema = new Schema(
{
wallet_id: { type: String, required: true },
category_id: { type: String, required: true },
user: { type: String, required: true },
amount: { type: Number, required: true },
type: { type: String, required: true },
date: {
type: String,
default: moment().format("YYYY-MM-DD"),
required: true,
},
description: { type: String, required: true },
},
{ timestamps: true }
)
Which is created like so :
const transaction = new TransactionModel(payload)
await transaction.save()
I also have a pre(“save”) middleware on the Transaction where im trying to modify the Wallet field based on the incoming new Transaction document, like updating the income,expenses values, incrementing totals etc..
transactionSchema.pre("save", async function (next) {
try {
const wallet = await model("wallet").findOne({ _id: this.wallet_id })
if(this.type === "expense"){
wallet.balance: -= transaction.amount
wallet.expenses: += transaction.amount
//wallet.income: //not used here
//wallet.income_transactions_count: //not used here
wallet.expenses_transactions_count: expenses_transactions_count += 1
wallet.transactions_count: number
await wallet.save()
}
///the same for income type etc
...
next()
} catch (error: any) {
next(error)
}
})
For some very curious reason, the fields income_transactions_count,expenses_transactions_count and transactions_count
sometimes change and sometimes dont.
The reason is that sometimes they have undefined values at the time i’m trying to modify them and the mind blowing thing is that when i log the value of wallet right after const wallet = await model...
i get all the values without issues, but when i do the same thing inside the if statement, ONLY those 3 return undefined and not every time ! Sometimes they have their correct values as expected !