Home > Mobile >  How do I update a document in MongoDB using Mongoose
How do I update a document in MongoDB using Mongoose

Time:06-07

I am creating a Car Booking Service. Here is the code for car Model.

    const mongoose = require('mongoose');
    const CarSchema = new mongoose.Schema({
      Name: {
          type: String,
          required: true
      },

    Model: {
        type: String,
        required: true
    },

    Year: {
        type: String,
        required: true
    },

    engine: {
        type: String,
        required: true
    },

    color: {
        type: String
    },

    status: {
        type: String,
        enum: ['available', 'unavailable'],
        default: 'available'
    },

    photos: [
        {
            type: String
        }
    ]
});

module.exports = mongoose.model('Car', CarSchema);

Here is the code for Booking.js

exports.Booking = async (req, res) => {
const { car, bookingDate, returnDate, location } = req.body;
try {
    let id = req.user;
    let user = await User.findById(id);
    let car = await Car.findById(req.body.car);

    if (!user || !car) {
        return res.status(400).json('This car is unavailable...');
    }

    let booking = await Booking.create({ user, car, bookingDate, returnDate, location });
    if (!booking) {
        return res.status(404).json({ message: 'failed to create booking' });
    }
    console.log(car.status);
    car.status = 'unavailable';
    console.log('Afterwards: ', car);
    return res.status(202).json({ message: 'Success', booking });
} catch (error) {
    return res.status(500).json(error.message);
}

};

After console logging the updated Car document it shows that the Car status is 'unavailable', but when I check my database the status update does not reflect so. Copy of the Car document in MongoDB

  {
"_id": "629dfa42e850785d3f3faa33",
"Name": "BMW",
"Model": "M8",
"Year": "2022",
"engine": "v8",
"color": "Black",
"status": "available",
"photos": [],
"__v": 0

},

Why is the car status not updating inside MongoDB?

CodePudding user response:

car.status = 'unavailable'; 

does not update details in DB. you need to perform update operation on Car model so details in DB will be updated.

Car.findOneAndUpdate({id:req.body.car},{status:'available'}),callback)

CodePudding user response:

you can use -> await Car.findOneAndUpdate({id:req.body.car},{status:'available'})

But you already find car doc, so should be like this;

car.status = 'unavailable';
await car.save(); // add this line

  • Related