How to save a property to a mongoose document post save How to save a property to a mongoose document post save mongoose mongoose

How to save a property to a mongoose document post save


After stepping away from the computer for a few hours I realized I was adding too much complexity and trying too hard to use the built-in timestamps option. I just changed my math to include Date.now() - this.createdAt, changed the post save to a pre save, and got rid of the extra applicant.save():

Applicant's Schema:

var applicantSchema = new Schema({    name: {        type: String,        required: true    },    email: {        type: String,        required: true,        lowercase: true    },    timeTaken: String}, {timestamps: true});applicantSchema.pre("save", function (next) {    this.setTimeTaken();    next();});applicantSchema.methods.setTimeTaken = function () {    var applicant = this;    var ms = Date.now() - this.createdAt;    var x = ms / 1000;    var seconds = Math.floor(x % 60);    x /= 60;    var minutes = Math.floor(x % 60);    x /= 60;    var hours = Math.floor(x % 24);    applicant.timeTaken = hours + "h:" + minutes + "m:" + seconds + "s";};

Applicant Router:

applicantRouter.put("/:applicantId", function (req, res) {    Applicant.findById(req.params.applicantId, function (err, applicant) {        applicant.save(function (err, applicant) {            if (err) {                res.status(500).send(err)            } else {                res.send({success: true, timeTaken: applicant.timeTaken})            }        });    });});

Works like a charm.