Reputation: 73
I have this Schema:
const opening_hourSchema = new Schema({
sunday: {open: { type: Boolean, default: true}, from: { type: String, default: "10:00"}, to: { type: String, default: "19:00"} },
monday: {open: { type: Boolean, default: true}, from: { type: String, default: "10:00"}, to: { type: String, default: "19:00"} },
tuesday: {open: { type: Boolean, default: true}, from: { type: String, default: "10:00"}, to: { type: String, default: "19:00"} },
wednesday: {open: { type: Boolean, default: true}, from: { type: String, default: "10:00"}, to: { type: String, default: "19:00"} },
thursday: {open: { type: Boolean, default: true}, from: { type: String, default: "10:00"}, to: { type: String, default: "19:00"} },
friday: {open: { type: Boolean, default: false}, from: { type: String, default: "10:00"}, to: { type: String, default: "19:00"} },
saturday: {open: { type: Boolean, default: false}, from: { type: String, default: "10:00"}, to: { type: String, default: "19:00"} },
}
, { timestamps: true });
I want to update it with an object that looks like this:
opening_hours:
friday: {open: false, from: "06:20", to: "13:00"}
monday: {open: false, from: "02:00", to: "09:00"}
saturday: {open: false, from: "07:00", to: "14:00"}
sunday: {open: false, from: "01:00", to: "08:00"}
thursday: {open: false, from: "05:00", to: "12:00"}
tuesday: {open: false, from: "03:00", to: "10:00"}
wednesday: {open: false, from: "04:00", to: "11:00"}
__proto__: Object
_id: "5fbd18517954d20024a132b4"
This is my function to accomplish the update.
router.post('/set-open-hours', auth, function (req, res) {
OpeningHours.findByIdAndUpdate(req.body._id , req.body.opening_hours)
.then((opening_hours) => {
res.json(opening_hours)
})
.catch(err => res.status(400).json("Error2: " + err));
})
The strange this is that it works, but takes two tries for some reason. If I call the function once it will return the old object. The second time around it will return the correct object, for some reason.
Upvotes: 2
Views: 373
Reputation:
This is because the findByIdAndUpdate() method returns that matched the condition before the update operation.
Model.findByIdAndUpdate(id, updateObj, {new: true})
{new: true} this will return the updated result.
Upvotes: 3