Jonathan Loiselle
Jonathan Loiselle

Reputation: 15

How can I inherit a schema but maintain separate collections using mongoose.js and node.js

I have a schema that I need to maintain as an exact copy of another schema, but keep these documents in separate collections.

var someSchema = mongoose.Schema({
    "foo": {"type": String, "required": true, "index": true},
    "bar": {"type": String, "required": true, "index": true},
});

The goal I'm after is a simple way to inherit the exact same schema to another model/collection without having to remember to update the second schema every time I make changes to the first.

i.e.

var someOtherSchema = mongoose.Schema( < some magic here >);

Upvotes: 1

Views: 573

Answers (1)

michelem
michelem

Reputation: 14590

Wrap it in an object and reuse the object:

var schemaObj = {
    "foo": {"type": String, "required": true, "index": true},
    "bar": {"type": String, "required": true, "index": true},
}

var someSchema = new mongoose.Schema(schemaObj, { collection: 'some' });    
var someOtherSchema = new mongoose.Schema(schemaObj, { collection: 'someOther' });

var someModel = mongoose.model('SomeModel', someSchema);
var someOtherModel = mongoose.model('someOtherModel', someOtherSchema);

Upvotes: 1

Related Questions