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

前端 未结 1 1039
一向
一向 2020-12-18 13:09

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 t

相关标签:
1条回答
  • 2020-12-18 13:35

    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.

    0 讨论(0)
提交回复
热议问题