Skip to content

Instantly share code, notes, and snippets.

@troyk
Created February 23, 2012 12:38
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save troyk/1892652 to your computer and use it in GitHub Desktop.
Save troyk/1892652 to your computer and use it in GitHub Desktop.
Mongoose multiple schemas in single collection
// Don't care much about inheritance at this point, but I'll probably attempt it at
// some point via cloning ancestor schema's
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var Contact = new Schema({
_type: String,
name: String
});
var Person = new Schema({
_type: {type: String, default: 'Person'},
name: {
first: String,
last: String
}
});
var Company = new Schema({
_type: {type: String, default: 'Company'},
name: String
});
Contact.methods.iam = function() { return 'Base'; };
Company.methods.iam = function() { return 'Company'; };
Person.methods.iam = function() { return 'Person'; };
var Base = mongoose.model('Contact', Contact, 'contacts');
var exports = module.exports = Base;
Base.Person = mongoose.model('Person', Person, 'contacts');
Base.Company = mongoose.model('Company', Company, 'contacts');
// Monkey path inheritance, seems to work
var init = Base.prototype.init;
init.Person = new Base.Person().__proto__;
init.Company = new Base.Company().__proto__;
Base.prototype.init = function (doc, fn) {
var obj = init.apply(this,arguments);
obj.__proto__ = init[doc._type];
return obj;
};
@fanghm
Copy link

fanghm commented Jul 13, 2016

Mongoose already supports multiple schemas for one collection: http://mongoosejs.com/docs/api.html#index_Mongoose-model

@NetPumi2
Copy link

NetPumi2 commented Mar 4, 2020

@NickSolante
Copy link

I dont quite understand @NetPumi2 @fanghm

@viradiya1993
Copy link

How to insert multiple document using mongoodb with node js API

@naveenxy
Copy link

insert multipe document using GRIDFS

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