Created
February 14, 2020 12:40
-
-
Save VonSwirl/e400b48d43e85bdb2b6741bda9367d68 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mongoose from 'mongoose' | |
/** | |
* Inherate from another existing mongoose schema | |
* @param {mongoose.Schema} parentSchema Any existing mongoose.Schema e.g UserSchema | |
* @param {{}} redefineOrAddFieldsOrEmpty see example below: | |
* @param {{}} options https://mongoosejs.com/docs/guide.html#options | |
* * ALLOWS: | |
* * Modifying Fields | |
* * Adding Fields | |
* * Adding Mongoose Options | |
* * Remove fields? (Untested/Unlikely) | |
* * USAGE | |
* @example | |
// Imported Example Schema to extend. | |
const UserSchema = new mongoose.Schema({ | |
firstname: {type: String}, | |
lastname: {type: String}, | |
phone: {type: String}, | |
email: {type: String, unique: true, required: true}, | |
passwordHash: {type: String, required: true} | |
}) | |
// Field are refined here. | |
const redefineOrAddFieldsOrEmpty = { | |
// Modified | |
firstname: { type: String, required: true }, | |
// Modified | |
lastname: { type: String, required: true }, | |
// Field Added | |
adminID: { type: Number, max: 0, min: 99999 required: true } | |
} | |
// Create the new Schema AdminUserSchema | |
// Which inherates from the UserSchema | |
// redefineOrAddFieldsOrEmpty take user define object to extend/modify | |
AdminUserSchema = extendSchema(UserSchema, redefineOrAddFieldsOrEmpty) | |
* @license MIT https://opensource.org/licenses/MIT | |
* @author Jerome Hurley | |
*/ | |
function extendSchema (parentSchema, redefineOrAddFieldsOrEmpty, options) { | |
return new mongoose.Schema(Object.assign({}, parentSchema.obj, redefineOrAddFieldsOrEmpty), options) | |
} | |
export default extendSchema |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment