Home > Net >  How to set a field value in mongoose model to be addition of two fields?
How to set a field value in mongoose model to be addition of two fields?

Time:12-08

I have two fields wallet and bank both stores a Integer. I want to insure that another field named total should have value of computed value of wallet and bank..

const mongoose = require('mongoose');
const User = new mongoose.Schema({
    id: { type: String, unique: true, required: true },
    wallet: { type: Number, default: 500 },
    bank: { type: Number, default: 0 },
    total: { type: Number},
})

module.exports = { User: mongoose.model("User", User) }

CodePudding user response:

Have a look at mongoose virtuals.

In your case it would look something like this:

const mongoose = require('mongoose');
const User = new mongoose.Schema({
    id: { type: String, unique: true, required: true },
    wallet: { type: Number, default: 500 },
    bank: { type: Number, default: 0 },
    total: { type: Number},
}, {
  virtuals: {
    total: {
      get() {
        return this.wallet   this.bank;
      }
    }
  }
})

module.exports = { User: mongoose.model("User", User) }

mongoose will call the getter function every time you access the total property

  • Related