Mongoose: extending schemas

前端 未结 9 485
轮回少年
轮回少年 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:41

    I didn't require discrimination, as I was trying to extend sub document schema's which are stored as a part of a parent document anyway.

    My solution was to append an "extend" method to the schema that is the base schema, so that you can either use the base schema itself or generate a new schema based on it.

    ES6 code follows:

    'use strict';
    
    //Dependencies
    let Schema = require('mongoose').Schema;
    
    //Schema generator
    function extendFooSchema(fields, _id = false) {
    
      //Extend default fields with given fields
      fields = Object.assign({
        foo: String,
        bar: String,
      }, fields || {});
    
      //Create schema
      let FooSchema = new Schema(fields, {_id});
    
      //Add methods/options and whatnot
      FooSchema.methods.bar = function() { ... };
    
      //Return
      return FooSchema;
    }
    
    //Create the base schema now
    let FooSchema = extendFooSchema(null, false);
    
    //Expose generator method
    FooSchema.extend = extendFooSchema;
    
    //Export schema
    module.exports = FooSchema;
    

    You can now use this schema as is, or "extend" it as needed:

    let BazSchema = FooSchema.extend({baz: Number});
    

    Extension in this case creates a brand new Schema definition.

提交回复
热议问题