Search code examples
node.jsmongoosemongoose-schema

How can I generate child model in mongoose


I'm trying to model the following.

I have a parent model that is called Brick that has some attributes. There will be 5+ type of bricks that will all have their own specific attributes which are needed also.

I want to be able to select all Bricks of a certain customer id later, whatever the type (TwitterBrick, facebookBrick et cetera) is.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// set up a mongoose model
module.exports = mongoose.model('Brick', new Schema({ 
    type: String, 
    userid: { type: String, required: true},
    animationspeed: { type: Number, min: 1, max: 100 }, 
    socialsite: String,     // none, twitter, instagram
    socialsearchtags: String,
    tagline: { type: String, minlength:3,maxlength: 25 },

}));

An example for a child is TwitterBrick. for now it is:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('TwitterBrick', new Schema({ 
    bgColor1: String, 
    bgColor2: String,
    bannerBgColor1: String,
    bannerBgColor2: String,
}));

TwitterBrick should inherit the attributes of Brick, but I don't know how. Can you help me in the right direction?

Thanks!


Solution

  • My solution was to set a new "content" field in brickSchema, and split in different files:

    brick.schema.js

    var mongoose = require('mongoose');
    
        module.exports = { 
              type: String, 
              userid: { type: String, required: true},
              animationspeed: { type: Number, min: 1, max: 100 }, 
              socialsite: String,     // none, twitter, instagram
              socialsearchtags: String,
              tagline: { type: String, minlength:3,maxlength: 25 },
              content: {type:mongoose.Schema.Types.Mixed, required: false, default: null}
        }
    

    brick.model.js

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    
    var BrickSchema = new Schema(require('brick.schema.js'));
    module.exports = mongoose.model('defaultBrick', BrickSchema, 'Bricks');
    

    twitterBrick.model.js

      var mongoose = require('mongoose');
      var Schema = mongoose.Schema;  
      var brickSchema = require('brick.schema.js');
    
      brickSchema.content = new Schema({
      bgColor1: String, 
      bgColor2: String,
      bannerBgColor1: String,
      bannerBgColor2: String,
    });
    
    var BrickSchema = new Schema(require('brick.schema.js'));
    module.exports = mongoose.model('twitterBrick', BrickSchema, 'Bricks');
    

    Hope it helps !