Mongoose: extending schemas

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

    All of these answers seem rather needlessly complicated, with extension helper functions or extend methods applied to the schema's or using plugins/discriminators. I've used the following solution instead which is simple, clean and easy to work with. It defines a blueprint for the base schema, and then the actual schema's are built using the blueprint:

    foo.blueprint.js

    module.exports = {
      schema: {
        foo: String,
        bar: Number,
      },
      methods: {
        fooBar() {
          return 42;
        },
      }
    };
    

    foo.schema.js

    const {schema, methods} = require('./foo.blueprint');
    const {Schema} = require('mongoose');
    const FooSchema = new Schema(foo);
    Object.assign(FooSchema.methods, methods);
    module.exports = FooSchema;
    

    bar.schema.js

    const {schema, methods} = require('./foo.blueprint');
    const {Schema} = require('mongoose');
    const BarSchema = new Schema(Object.assign({}, schema, {
      bar: String,
      baz: Boolean,
    }));
    Object.assign(BarSchema.methods, methods);
    module.exports = BarSchema;
    

    You can use the blueprint for the original schema as is, and using Object.assign you can extend the blueprint in any way you like for other schema's, without modifying the same object.

提交回复
热议问题