Home > Net >  How should I change the value of the field before saving it to database?
How should I change the value of the field before saving it to database?

Time:10-28

I am new to Node.js and I'm trying to perform CRUD operation right now. I have this function to save data to the mongoDB database but the thing is I'm trying to change the value of one particular field before saving it to database. The problem is that my data is getting saved first and then the calculations are being performed. Here is my post function:

router.post('/', async(req, res) => {
    const reservation = new Reservation({
        guestID: mongoose.Types.ObjectId(req.body.guestID),
        roomID: mongoose.Types.ObjectId(req.body.roomID),
        checkIn: req.body.checkIn,
        checkOut: req.body.checkOut,
        numberOfAdults: req.body.numberOfAdults,
        totalCost: req.body.totalCost,
        numberOfChildren: req.body.numberOfChildren
    })
    try
    {
        
        const reservationRecord = await reservation.save()
        res.json(reservationRecord)
    }
    catch(err)
    {
        console.log(err)
        res.send("Error")
    }
})

And here is the Schema

const mongoose = require('mongoose')
const axios = require('axios')

const reservationSchema = new mongoose.Schema({
    guestID: {
        type: mongoose.SchemaTypes.ObjectId,
        required: true
    },
    roomID: {
        type: mongoose.SchemaTypes.ObjectId,
        required: true
    },
    checkIn: {
        type: Date,
        required: true
    },
    checkOut: {
        type: Date,
        required: true
    },
    numberOfAdults: {
        type: Number,
        required: true
    },
    numberOfChildren: {
        type: Number,
        required: true
    },
    totalCost: {
        type: Number,
        required: false,
        default: 0
    }
})
reservationSchema.pre('save', function(next){
        var date1 = new Date(this.checkIn);
        var date2 = new Date(this.checkOut);
        var diff = Math.abs(date1.getTime() - date2.getTime());
        var diffDays = Math.ceil(diff / (1000 * 3600 * 24));
        console.log(diffDays)
        var roomCost
        var totalRoomCost 
        axios.get("http://localhost:5555/rooms/"   this.roomID).then((response) => {
                console.log(response)
                roomCost = response.data.cost;
                console.log("room cost is "   roomCost)
                totalRoomCost = (this.numberOfAdults   this.numberOfChildren) * response.data.cost * diffDays
                this.totalCost = totalRoomCost
            })
            //this.totalCost = (this.numberOfAdults   this.numberOfChildren) * roomCost * diffDays
            console.log(this.totalCost)
            next()
})
const Reservation = mongoose.model('reservation', reservationSchema)

module.exports = Reservation

I want to change the value of totalCost before saving it to database. Can somebody let me know what the problem is with the code? Thank you!

CodePudding user response:

You should just handle the calculations in your POST method, before your create your new Reservation instance:

router.post('/', async (req, res) => {
  try {
    const {
      numberOfChildren,
      numberOfAdults,
      roomID,
      checkIn,
      checkOut,
    } = req.body;

    var date1 = new Date(checkIn);
    var date2 = new Date(checkOut);
    var diff = Math.abs(date1.getTime() - date2.getTime());
    var diffDays = Math.ceil(diff / (1000 * 3600 * 24));

    const room = await Room.findById(roomID)

    const newTotalCost = (numberOfAdults   numberOfChildren) * room.cost * diffDays;
    const reservation = new Reservation({
      ...req.body,
      totalCost: newTotalCost,
    });
    const reservationRecord = await reservation.save();
    res.json(reservationRecord);
  } catch (err) {
    console.log(err);
    res.send('Error');
  }
});

Of course, the reservationSchema.pre('save') function is unecessary in this case.

  • Related