mongoose Mongoose Schemas Saving Current Time and Update Time


This kind of schema will be useful if you want to keep trace of your items by insertion time or update time.

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;

// Creates a User Schema.
var user = new Schema({
                       name: { type: String },
                       age : { type: Integer},
                       sex : { type: String },
                       created_at: {type: Date, default:},
                       updated_at: {type: Date, default:}

// Sets the created_at parameter equal to the current time
user.pre('save', function(next){
    now = new Date();
    this.updated_at = now;
    if(!this.created_at) {
        this.created_at = now

module.exports = mongoose.model('user', user);