Created
July 31, 2012 00:36
-
-
Save jksdua/3212291 to your computer and use it in GitHub Desktop.
Mongoose schema inheritance example
This file contains hidden or 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
"use strict"; | |
var mongoose = require('mongoose'), | |
Schema = mongoose.Schema; | |
// ==== connect to database ==== | |
mongoose.connect('mongodb://localhost/temp'); | |
// ==== base object to be inherited ==== | |
var baseObj = { | |
a : Number, | |
b : String | |
}; | |
// ==== inherit objects as needed at runtime ==== | |
// inherited objects | |
var objA = Object.create(baseObj); | |
objA.c = [Number]; | |
var objB = Object.create(baseObj); | |
objB.c = String; | |
// create schema and model | |
var SchemaA = new Schema(objA), | |
modelA = mongoose.model('modelA', SchemaA, 'collectionAB'); | |
var SchemaB = new Schema(objB), | |
modelB = mongoose.model('modelB', SchemaB, 'collectionAB'); | |
// save a record | |
var recordA = new modelA({ | |
a : 1 | |
, b : 'a' | |
, c : [1,2,3] | |
}); | |
var recordB = new modelB({ | |
a : 2 | |
, b : 'z' | |
, c : 'c' | |
}); | |
recordA.save(); | |
recordB.save(); | |
// ==== output from mongo console ==== | |
/* > db.collectionAB.find() | |
{ "a" : 1, "b" : "a", "_id" : ObjectId("501727f26a5ec8e189000001"), "c" : [ 1, 2, 3 ] } | |
{ "a" : 2, "b" : "z", "c" : "c", "_id" : ObjectId("501727f26a5ec8e189000002") } | |
*/ |
This no longer appears to work (using mongoose 3.6.11).
Have a look at
https://github.com/briankircho/mongoose-schema-extend
This still works in 2018, mongoose 5.0.12 Use only object.assign() instead of Object.create().
const baseObj:any = {
a :{ type: Number, required: false},
b : { type: String, required: false }
};
// inherited objects
const objA:any = Object.assign(baseObj);
objA.extra = {
value: { type: String, required: false }
}
const schema:Schema = new Schema( objA );
export mongoose.model('ModelA', schema, 'collection');
`
Very helpful
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Perfect. Simple, straightforward, and it works.