I have the following model for users:
var UserSchema = new mongoose.Schema({
name: String,
dob: Date,
sex: String,
photo: String,
email:
findOneAndUpdate
simply sends a MongoDB findAndModify
request (see findOneAndUpdate). What this means is that it skips all the mongoose magic involved with the schema setters, getters, defaults, etc. Validation is only run on create/save so the way around this is to do a .findOne()
, check existence/create a new one, and then .save()
.
see this issue for more discussion
EDIT:
In regards to the first question about changing the date each time, you could change the schema a bit. Get rid of the default value, and instead add this after declaring the schema:
UserSchema.pre("save", function (next) {
if (!this.created) {
this.created = new Date();
}
next();
});
That will only create a date if the created:
value is not present, and should prevent it from changing the creation date each time (when using .save()
).
see Mongoose middleware