Mongoose Model inheritance: How to put an extended model in its own file?

1.8k views Asked by At

I am trying to use inheritance with Mongoose in an Express app and my starting point is this discussion on GitHub where they discuss how the feature is implemented.

My model is simple: an abstract BookableAbstractSchema schema, and a MeetingRoom schema that extends Bookable.

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

// Define our user schema
var BookableAbstractSchema = function (){
    Schema.apply(this,arguments);
    this.add({
        spaceId: {type: mongoose.Schema.Types.ObjectId, ref: 'Space'},
        name: {
            type: String,
            required: true
        }

    });
}
util.inherits(BookableAbstractSchema, Schema);

var BookableSchema = new BookableAbstractSchema();
var bookable = mongoose.model('bookable', BookableSchema);


// MEETING ROOM
var MeetingRoomSchema = new BookableAbstractSchema({
    something:String
});

var meetingRoom = bookable.discriminator('MeetingRoom', MeetingRoomSchema);
module.exports.MeetingRoom = meetingRoom;

Until then it works great.

I am having dificulty when I want to put each Schema in its own file

bookable.js

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

// Define our user schema
var BookableAbstractSchema = function (){
    Schema.apply(this,arguments);
    this.add({
        spaceId: {type: mongoose.Schema.Types.ObjectId, ref: 'Space'},
        name: {
            type: String,
            required: true
        }

    });
}
util.inherits(BookableAbstractSchema, Schema);

var BookableSchema = new BookableAbstractSchema();
module.exports= mongoose.model('bookable', BookableSchema);

meetingroom.js

var mongoose = require('mongoose');
var Bookable = require('./bookable');

var MeetingRoomSchema = new Bookable({
    something:String
});

module.exports = Bookable.discriminator('MeetingRoom', MeetingRoomSchema); // error described below is thrown here.

But then I get the following error in the console:

throw new Error("You must pass a valid discriminator Schema");

When I debug, 'MeetingRoom' is indeed an instance of model, not schema

This is where I am getting lost and I need help :) Why does this work when it's all in the same file and not when the models are separated in different files?

1

There are 1 answers

0
shaond On

The MeetingRoomSchema actually needs to be of the type mongoose.Schema, not a new Bookable Object.

Here's the relevant validation in mongoose's source code:

  if (!(schema instanceof Schema)) {
    throw new Error("You must pass a valid discriminator Schema");
  }

The above is referenced from these mongoose docs

Therefore, MeetingRoomSchema should be defined as below:

var MeetingRoomSchema = new mongoose.Schema({
  something: String
});

module.exports = Bookable.discriminator('MeetingRoom', MeetingRoomSchema);

Hope this helps!