Sunday, 2 April 2017

Cannot create mongo model using discriminator mongoose

I am trying to create a collection named entities, which could have three different types music,sports,teams

My schema is as follows,

TestSchema.js

const mongoose = require('mongoose'),
      extend = require('mongoose-schema-extend');
const Schema = mongoose.Schema;

var EntitySchema = new Schema({
    entityId: {
        type: String
    },
    name: {
        type: String
    },
    description: {
        type: String
    },
    type: {
        type: String
    },
    subcategory: {
        type: String
    }
}, {collection : 'entities', discriminatorKey : '_type' });
module.exports.schema = EntitySchema;
module.exports.model = mongoose.model('newEntity', EntitySchema);

And i am trying to extend the above with the following schema,

musicEntity.js

module.exports = function (dbService) {
    const mongoose = require('mongoose'),
        extend = require('mongoose-schema-extend');
    const Schema = mongoose.Schema;
    const EntitySchema = require('./testSchema').schema;
    try {
        model = dbService.getModel(modelName);

    } catch (error) {
        var MusicSchema = EntitySchema.extend({
            category: {
                type: String
            }
        });       
        model = dbService.createModel('Music', MusicSchema, {
            name: 'text'
        }, '_Music');
    }
    return model;
};

dbservice.js

'use strict';
(function () {
    let dbHelper = require('./DbHelper');
    module.exports = {
        createModel: function (modelName, entityDef, indexObject, collection) {
            return dbHelper.createModel(modelName, entityDef, indexObject, collection);
        }
    };
}())

and DbHelper.js

'use strict';
(function () {
    var mongoose = require('mongoose');   
    module.exports = { 
        createModel: function (modelName, schemaObject, indexObject, collection) {
            var modelSchema = new mongoose.Schema(schemaObject);
            if (indexObject) {
                modelSchema.index(indexObject);
            }
            return collection ? mongoose.model(modelName, modelSchema, collection) : mongoose.model(modelName, modelSchema);
        }
    }
}());

When i invoke the above in main.js

 let musicEntityModel = require(__dirname +  'models/musicEntity')
 dbService.query(musicEntityModel , {'entityId': entityId}, {}, {});

it throws an errror saying **

'TypeError: Undefined type `undefined` at `paths`',
  'Did you try nesting Schemas? You can only nest using refs or arrays.',

**



via Sajeetharan

No comments:

Post a Comment