Here is the mongodb document that I want to update through mongoose:
My model:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const reservationSchema = new Schema({
username: {
type: String,
required: true,
},
name: {
type: String,
required: true,
},
timeStart: {
type: String,
required: true,
},
timeEnd: {
//NOT REQUIRED
type: String,
},
date: {
type: String,
required: true,
},
venue: {
type: String,
required: true,
},
seat: {
type: String,
required: true,
},
});
module.exports = mongoose.model("Reservation", reservationSchema);
Using the findOneAndUpdate function, I am trying to find one document in the reservations collection by username and timeEnd, such that username is P19010770 and timeEnd should be an empty string.
Then, I want to update the timeEnd with the value passed in the req.body. But my timeEnd does not get update using the following code (it’s still an empty string…)
Code to update (does not work):
This is where username and timeEnd values are passed from:
I’ve spent hours trying to find the problem but I still could not get what went wrong. Please help!
UPDATE:
I tried to directly find the document using { _id: "64a82c5fc8b7aa7823d82a34" }
, and timeEnd got successfully updated… so this means that there is something wrong with the filter part..?
2
Answers
findOneAndUpdate() takes 4 arguments in which two are necessary and 2 are optinal.
Where filter and update are must be specified.
while two other args are options and callback.
Where filter gives the first document with the given criteria and it updates that document with given update data.
All your logic and code are correct but you do not have to use $set while using findOneAndUpdate(). Mongoose automatically updates the attribute of document with given update query.
Checkout this documentation of mongoose findOneAndUpdate()
So, your code will be
Your code is syntatically is correct,
but their is possiblility that in you database there are many records with same username and empty timeEnd
so it is updated another record
you can use below code for now this will also work
and pass option true to get update record in same db call for updated record