如何使用 Mongoose 更新 MongoDB 中的文档

格雷格区

我正在创建汽车预订服务。这是汽车模型的代码。

    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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用Mongodb / Mongoose中的子文档处理深度更新?

如何使用 mongoose 更新 MongoDB 中的数组?

更新子文档中的数组-mongoose mongodb

如何使用 mongoose 在单个 mongodb 文档中更新数组中的多个对象

如何在MongoDB(Mongoose)中更新和更新文档。节点JS

使用 mongoose 更新 mongoDB 中的数组

MongoDB-Mongoose:如何使用Mongoose同时更新两个单独的嵌入式文档?

使用Mongoose在MongoDB中查询引用的文档

使用mongoose通过更新方法向mongodb中的现有文档添加新字段

mongodb、mongoose、express、nodejs 使用旧值更新多个文档中的字符串

在 MongoDB 中更新 Mongoose 子文档时使用 POST 还是 PUT 有关系吗?

如何使用MongoDB(Mongoose)在集合中添加/更新ObjectId数组?

如何使用Mongoose更新MongoDB中的一个属性?

如何在Mongoose中更新/上传文档?

使用Mongoose更新数组中的子文档

使用 findOne() 后如何从 mongoose/mongodb 文档中获取值

使用 mongoose 在 MongoDB 上更新

MongoDB:如何更新集合中的整个文档

如何更新mongodb中的文档字段?

如何在mongodb中更新子文档

如何更新MongoDB文档中的数组元素

如何更新MongoDB集合中的每个文档?

如何更新 mongodb atlas 文档中的值?

使用Java更新MongoDB中的文档

通过提供正文mongoose / mongodb中的文档来更新多个文档

如何在mongoDB或Mongoose中更新嵌套数组的值

使用Mongoose和Node.js更新MongoDB中的数据

什么是使用Mongoose更新MongoDB中许多记录的正确方法

是否可以在post方法中更新mongodb集合(使用Mongoose)?