Skip to content

Instantly share code, notes, and snippets.

@jksdua
Created July 31, 2012 00:36
Show Gist options
  • Save jksdua/3212291 to your computer and use it in GitHub Desktop.
Save jksdua/3212291 to your computer and use it in GitHub Desktop.
Mongoose schema inheritance example
"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") }
*/
@aab595
Copy link

aab595 commented Dec 28, 2021

Very helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment