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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…