Note that there are some explanatory texts on larger screens.

plurals
  1. POMongoose: extending schemas
    text
    copied!<p>Currently I have two almost identical schemas:</p> <pre><code>var userSchema = mongoose.Schema({ email: {type: String, unique: true, required: true, validate: emailValidator}, passwordHash: {type: String, required: true}, firstname: {type: String, validate: firstnameValidator}, lastname: {type: String, validate: lastnameValidator}, phone: {type: String, validate: phoneValidator}, }); </code></pre> <p>And</p> <pre><code>var adminSchema = mongoose.Schema({ email: {type: String, unique: true, required: true, validate: emailValidator}, passwordHash: {type: String, required: true}, firstname: {type: String, validate: firstnameValidator, required: true}, lastname: {type: String, validate: lastnameValidator, required: true}, phone: {type: String, validate: phoneValidator, required: true}, }); </code></pre> <p>Their only difference is in validation: Users do not need a firstname, lastname or phone. Admins however must have these properties defined.</p> <p>Unfortunately the above code is not very DRY, as they're almost identical. Therefore I am wondering if it is possible to build an <code>adminSchema</code> based on the <code>userSchema</code>. E.g.:</p> <pre><code>var adminSchema = mongoose.Schema(userSchema); adminSchema.change('firstname', {required: true}); adminSchema.change('lastname', {required: true}); adminSchema.change('phone', {required: true}); </code></pre> <p>Obviously that's just pseudocode. Is something like this possible?</p> <p>Another very similar question is if it is possible to create a new schema based on another, and add some more properties to it. For example:</p> <pre><code>var adminSchema = mongoose.Schema(userSchema); adminSchema.add(adminPower: Number); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload