Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format data in Model before saving in Mongoose (ExpressJS)

I get Date from user in the string format and I currently convert into a Date in controller before creating the Schema object and saving. Is there a way to move this logic to model as it seems to me that Model is the right place for this

var RunSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    starttime: {
        type: Date,
        default: Date.now
    }

});

Currently I do this

//req.body = {starttime;'2.05.2013 11:23:22'}
var run = new Run(req.body);
// util.getDate(datetime) returns false if invalid and Date() if valid
// req.body.starttime = '2.05.2013 11:23:22';
run.starttime = util.getDate(req.body.starttime);
run.save(function(err) {
    if(err) {
    } else {
    }
});

On a sidenote, how do I assert if I want to process the param in custom function checks. Something like

    req.assert('name', 'Name can\'t be empty').len(1, 1000);
like image 377
raju Avatar asked Nov 02 '25 17:11

raju


1 Answers

While I'm not sure about the meaning of req.body.starttime, I'm pretty sure you're looking for the Schema objects pre() function which is part of the Mongoose Middleware and allows the definition of callback functions to be executed before data is saved. Probably something like this does the desired job:

var RunSchema = new Schema({
  [...]
  starttime: {
    type: Date,
    default: Date.now
  }
});

RunSchema.pre('save', function(next) {
  this.starttime = new Date();
  next();
});

Note that the callback function for the save event is called every time before a record is created or updated. So this is for example the way for explicitly setting a "modified" timestamp.

EDIT:

Thanks to your comment, I now got a better understanding of what you want to achieve. In case you want to modify data before it gets assigned and persisted to the record, you can easily utilize the set property of the Schema:

// defining set within the schema
var RunSchema = new Schema({
  [...]
  starttime: {
    type: Date,
    default: Date.now,
    set: util.getDate
  }
});

Assuming that the object util is within scope (required or whatever) your current implementation fits the signature for the property set:

function set(val, schemaType)

The optional parameter schemaType allows you to inspect the properties of your schema field definition if the transform process depends on it in any way.

like image 72
matthias Avatar answered Nov 05 '25 09:11

matthias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!