I want that if one field value is updated so another field value is automatically updated by calculating automatically?

const mongoose = require("mongoose");
const paymentStatues = {
  0: "Normal",
  1: "Internal Collection",
  2: "External Collection",
  3: "Legal Collection",
}
const requestSchema = mongoose.Schema({
  customer: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Customer",
  },
  product: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Product",
  },
  profit: {
    type: Number
  },

  downPayment: {
    type: Number,
    default: 0
  },
  planOfInstallment: {
    type: Number
  },
  moneyRequiredToPay: { // This will be the whole money which i need from the customer exclude the downpayment and add the profit
    type: Number,
    default: 0,
  },
  paymentschedule: [
    {
      monthName: String,
      dateToPay: {
        type: Date,
      },
      paid: {
        type: Boolean,
        default: false
      },
      payment: {
        type: Number
      },
      paymentRecieveDate: {
        type: Date,
      },
    }
  ],
  contractInitiated: {
    type:Boolean,
    default: false
  },
  contractStatus: {
    type: String,
    default: "Normal"
  },
  moneyRecieved: { // calculator
    type: Number,
    default: 0,
  },
  moneyLeft: {
    type: Number,
  },

  investor: [{
    investorDetail: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Investor",
    },
    money: {
      type: Number,
      default: 0
    },
    date: {
      type: Date,
      default: Date.now()
    }
  }],
  
  documentContract: [
    {
       dept: {
        type: String,
       },
       recieveForm: {
        type: String
       },
       aggrement: {
        type: String
       }
    }
  ],
  createdDate: {
    type: Date,
    default: Date.now()
  }

});

requestSchema.virtual("id").get(function () {
  return this._id.toHexString();
});

requestSchema.set("toJSON", {
  virtuals: true,
});
exports.Request = mongoose.model("Request", requestSchema);

This is my schema and i want that in this schema some fields are like if on the field is updated from frontend so the other fields is updated automatically like subtracting or adding some money in field etc etc.

Hello @arbabmuhammad_ramzan, Welcome to MongoDB Community Forum,

I can see you are using mongoose NPM, So there is a middleware feature,

You can set pre-middleware for your schema and do whatever your logic before query updates in the database,

Types of middlewares you can create for your requirement,

  • save
  • update
  • updateOne
  • updateMany

Ex:

requestSchema.pre('updateOne', function(next) {
  // do stuff
  next();
});

I have used this one but its not working can you please check that ?

const mongoose = require("mongoose");
const investorSchema = mongoose.Schema({
  username: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  phoneNumber: {
    type: String,
    required: true,
  },
  passwordHash: {
    type: String,
    required: true,
  },
  money: { type: [mongoose.Schema.ObjectId], ref: 'Money' },
  totalMoney: {
    type: Number,
  },
  verified: {
    type: Boolean,
    default: false
  },
  document: [
    {
      cpr: {
        type: String,
      },
      passport: {
        type: String,
      },
      salarySlip: {
        type: String,
      }
    }
  ],
});
investorSchema.pre("updateOne", async function(done){
  if(this.isModified("money")){
    const getAllMoney = await this.get("money");
    console.log("money",money)
    const getTotalMoney = getAllMoney?.map(item => item?.value);
    this.set("totalMoney", getTotalMoney)
  }
  done()
})
investorSchema.virtual("id").get(function () {
  return this._id.toHexString();
});

investorSchema.set("toJSON", {
  virtuals: true,
});
exports.Investor = mongoose.model("Investor", investorSchema);

This is a different schema than your first post, I can see the money field has reference to another schema,

I am not sure when that money schema will update, i think you should update totalMoney field when the money schema updated the amount.

Hey,
Thanks its work

1 Like