Mongoose: how to achieve multi-level schema inheritance or compose?

Created on 4 Apr 2018  路  2Comments  路  Source: Automattic/mongoose

i have read mongoose document once by once.
Summary:
there are 4 possible solution

            |
  creativeworkSchema
            |
      ArticleSchema

So, @mongoosejs team, can you explain more much inheritance or compose with shcema?

Most helpful comment

@anlexN populate and plugins aren't really a mechanism for inheritance. Discriminators are used if you want to have multiple types of documents in a single collection, but that's a special case of general schema inheritance. IMO the below would be the cleanest way to do generic schema inheritance:

const mongoose = require('mongoose');

class thingSchema extends mongoose.Schema {
  constructor(obj, options) {
    super(obj, options);
    this.add({ test: String });
  }
}

class creativeWorkSchema extends thingSchema {
  constructor(obj, options) {
    super(obj, options);
    this.add({ test2: String });
  }
}

const schema = new creativeWorkSchema();

const Model = mongoose.model('Test', schema);

console.log(new Model({ test: 'abc', test2: 'abc' }));

All 2 comments

Hi @anlexN a similar question came up not too long ago and I just recently had the time to look into it. check out this comment for a working example of multi-level schema inheritance using custom SchemaTypes.

@anlexN populate and plugins aren't really a mechanism for inheritance. Discriminators are used if you want to have multiple types of documents in a single collection, but that's a special case of general schema inheritance. IMO the below would be the cleanest way to do generic schema inheritance:

const mongoose = require('mongoose');

class thingSchema extends mongoose.Schema {
  constructor(obj, options) {
    super(obj, options);
    this.add({ test: String });
  }
}

class creativeWorkSchema extends thingSchema {
  constructor(obj, options) {
    super(obj, options);
    this.add({ test2: String });
  }
}

const schema = new creativeWorkSchema();

const Model = mongoose.model('Test', schema);

console.log(new Model({ test: 'abc', test2: 'abc' }));
Was this page helpful?
0 / 5 - 0 ratings