Mongoose model inheritance: how to host extended model in its own file?

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

My model is simple: the abstract BookableAbstractSchema schema and the 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 have dificulty when I want to put each circuit 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 model

and notschema

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

+3


source to share


1 answer


It MeetingRoomSchema

should actually be of a type mongoose.Schema

, not a new object Bookable

.

Here's the relevant check in Mongoose source code:

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

      

The above links link to these mongoose docs



Therefore, MeetingRoomSchema

it should be defined as follows:

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

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

      

Hope this helps!

+2


source







All Articles