Why wouldn’t mongoDB update the “Date” field of my user entry? Why wouldn’t mongoDB update the “Date” field of my user entry? mongoose mongoose

Why wouldn’t mongoDB update the “Date” field of my user entry?


I was having a similar issue recently and haven't figured out the actual reason behind this, but as a workaround try telling mongoose explicitly that the expirationDate-field was changed:

req.user.expirationDate = new Date(    req.user.expirationDate.setDate(req.user.expirationDate.getDate() + 30));req.user.markModified('expirationDate');await req.user.save();

EDIT:

Just debugged it again and I think the reason behind this behaviour is your default value for expirationDate. Try passing it the Date.now function instead of immediately setting it to a new date:

expirationDate: {type: Date, default: Date.now},

This fixed it for me without having to use markModified().


Although we still have some unsolved issues on why the same set of codes works differently. I have decided not to deal with it for the moment. Here's my solution to the original problem: change the datatype from Date to String. Here's the new set of codes:

Creating User schema at the frontend:

const userSchema = new Schema(  {    profileId: String,    expirationDate: { type: String, default: new Date().toDateString() },    credits: { type: Number, default: 0 },  },  { timestamps: { createdAt: "created_at" } });

Updating user at the backend to MongoDB Atlas::

d = new Date(req.user.expirationDate);req.user.expirationDate = new Date(    d.setDate(d.getDate() + 30)  ).toDateString();  req.user.credits += 1;const user = await req.user.save();console.log(typeof req.user.expirationDate);//Checking the datatype of "expirationDate"