Mongoose: extending schemas

前端 未结 9 483
轮回少年
轮回少年 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条回答
  •  旧时难觅i
    2020-12-05 10:30

    You can create a Schema Factory function that accepts a Schema definition and optional schema options, which then merges the passed in Schema definition and options with the Schema fields and options which you want to share across schemas. Example illustrating this (assuming you want to share or extend a schema that has the fields email and is_verified and the timestamps option enabled):

    // schemaFactory.js
    const mongoose = require('mongoose');
    
    const SchemaFactory = (schemaDefinition, schemaOptions) => {
      return new mongoose.Schema({
        {
          email: {type: String, required: true},
          is_verified: {type: Boolean, default: false},
          // spread/merge passed in schema definition
          ...schemaDefinition
        }
      }, {
        timestamps: true,
        // spread/merge passed in schema options
        ...schemaOptions
      })
    }
    module.exports = SchemaFactory; 
    

    The SchemaFactory function can then be called with:

    // schemas.js
    const SchemaFactory = require("./schemaFactory.js")
    
    const UserSchema = SchemaFactory({
      first_name: String,
      password: {type: String, required: true}
    });
    
    const AdminSchema = SchemaFactory({
      role: {type: String, required: true}
    }, {
      // we can pass in schema options to the Schema Factory
      strict: false
    });
    

    Now the UserSchema and AdminSchema will contain both the email and is_verified field as well as have the timestamps option enabled, along with the schema fields and options you pass along.

提交回复
热议问题