节省当前时间和更新时间

如果你希望通过插入时间或更新时间跟踪项目,则此类架构将非常有用。

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);