D
D
Dmitrii Solovev2015-12-30 17:47:19
JavaScript
Dmitrii Solovev, 2015-12-30 17:47:19

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// Итого
});

Transaction scheme:
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'
  }
});

Since when adding each transaction, the account is updated with the addition of a new link to the array of transactions
yield mongoose.models.Account.findByIdAndUpdate(transaction.account, {
      $pull: {transactions: transaction._id}
    });

I tried to hang accountSchema.post middleware on all requests.
accountSchema.post('update', fn);
But this does not get the document, as in the case of save and remove, but the query (Query). How to implement correctly help?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Shatokhin, 2016-01-04
@dimonnwc3

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 question

Ask a Question

731 491 924 answers to any question