Mongoose: extending schemas

前端 未结 9 478
轮回少年
轮回少年 2020-12-05 10:10

Currently I have two almost identical schemas:

var userSchema = mongoose.Schema({

    email: {type: String, unique: true, required: true, validate: emailVal         


        
9条回答
  •  臣服心动
    2020-12-05 10:48

    To add to this discussion, you can also override mongoose.Schema with a custom base schema definition. For code compatibility, add the if statement that allows a Schema to be instantiated without new. While this can be convenient, think twice before doing this in a public package.

    var Schema = mongoose.Schema;
    
    var BaseSyncSchema = function(obj, options) {
    
        if (!(this instanceof BaseSyncSchema))
            return new BaseSyncSchema(obj, options);
    
        Schema.apply(this, arguments);
    
        this.methods.update = function() {
            this.updated = new Date();
        };
    
        this.add({
            updated: Date
        });
    };
    util.inherits(BaseSyncSchema, Schema);
    
    // Edit!!!
    // mongoose.Schema = BaseSyncSchema; <-- Does not work in mongoose 4
    // Do this instead:
    Object.defineProperty(mongoose, "Schema", {
        value: BaseSyncSchema,
        writable: false
    });
    

提交回复
热议问题