簡體   English   中英

帶有 mongoDB 的后端節點 js,補丁請求不更新日期類型值

[英]backend node js with mongoDB, patch request does not update date type value

我使用 node.js 構建后端並將數據保存在 MongoDB 中。 當我執行補丁請求時,我可以更改除日期類型之外的所有其他類型字段的值。

這是補丁請求的后端代碼。

router.patch('/:id', isLoggedIn, async (req, res) => {
    try {
        const updatedBooking = await Booking.updateOne(
            {_id: req.params.id},
            {
                $set: {userEmail: req.body.userEmail},  
                $set: {shiftDate: req.body.shiftDate},
                $set: {isMorningShift: req.body.isMorningShift}
            }
        );
        res.json(updatedBooking);
    } catch (err) {
        res.send({message: err});
    }
});

這是數據庫方案:

const BookingSchema=mongoose.Schema({
    userEmail:{
        type:String,
        required:true
    },
    shiftDate:{
        type:Date,
        required:true
    },
    isMorningShift:{
        type: Boolean,
        required: true
    }
});

MongoDB 中的對象如下所示:

 {
    "_id": "61787183e67b6822180175f9",
    "userEmail": "admin2@parantion.nl",
    "isMorningShift": false,
    "__v": 0,
    "shiftDate": "2066-06-23T00:00:00.000Z"
}

可能是什么問題?

更改行:

$set: {shiftDate: req.body.shiftDate}

$set: {shiftDate: new Date(req.body.shiftDate)}

或者

$set: {shiftDate: new Date()} 

不是多個$set ,而是將所有鍵更新為一個,

const updatedBooking = await Booking.updateOne(
            {_id: req.params.id},
            {
                $set: {
                       userEmail: req.body.userEmail,  
                       shiftDate: new Date(req.body.shiftDate),
                       isMorningShift: req.body.isMorningShift
               }
            }
        );

@ fractal397 的答案將正常工作。 如果你想要一個更干凈的代碼,你可以使用它。

const bookingId = req.params.id;
const payload =
   userEmail: req.body.userEmail,  
   shiftDate: new Date(req.body.shiftDate),
   isMorningShift: req.body.isMorningShift
}
const booking = await Booking.findByIdAndUpdate(bookingId, payload);

PS - 在 Mongoose 4.0 之后, findByIdAndUpdate 的new值默認更改為false 所以在這個操作中,數據庫中的數據將被更新,但它會返回舊值booking 為了獲得更新的價值作為回應,你將不得不這樣做 -

const booking = await Booking.findByIdAndUpdate(bookingId, payload, { new : true });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM