節省當前時間和更新時間

如果你希望通過插入時間或更新時間跟蹤專案,則此類架構將非常有用。

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: Date.now},
                       updated_at: {type: Date, default: Date.now}
});

// 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
    }
    next();
});

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