Answer the question
In order to leave comments, you need to log in
How to automatically update a field in MongoDB?
Hello. I am learning NodeJS and MongoDB with it. I wanted to write a small finance manager. It has a couple of mongoose schemas.
Tell me how to make it so that when adding new transactions, for each account, the fields spent, earned, summary are automatically recalculated?
Account scheme.
let accountSchema = new mongoose.Schema({
name: String,
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
transactions: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Transaction'
}],
spent: Number, // Потрачено
earned: Number, // Заработано
summary: Number// Итого
});
let transactionSchema = new mongoose.Schema({
amount: Number, // Количество
type: {
type: String,
enum: {
values: ['spent', 'earned', 'transfer']
}
},
description: String,
account: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Account'
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
yield mongoose.models.Account.findByIdAndUpdate(transaction.account, {
$pull: {transactions: transaction._id}
});
accountSchema.post('update', fn);
Answer the question
In order to leave comments, you need to log in
You can use $inc when adding
https://docs.mongodb.org/v3.0/reference/operator/u...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question