我正在创建汽车预订服务。这是汽车模型的代码。
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);
这是 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);
}
};
在控制台记录更新的 Car 文档后,它显示 Car 状态为“不可用”,但是当我检查我的数据库时,状态更新并没有反映出来。MongoDB 中 Car 文档的副本
{
"_id": "629dfa42e850785d3f3faa33",
"Name": "BMW",
"Model": "M8",
"Year": "2022",
"engine": "v8",
"color": "Black",
"status": "available",
"photos": [],
"__v": 0
},
为什么 MongoDB 中的汽车状态没有更新?
你可以使用->await Car.findOneAndUpdate({id:req.body.car},{status:'available'})
但是你已经找到了car doc,所以应该是这样的;
car.status = 'unavailable';
await car.save(); // add this line
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句