janez89 / mongoose-materialized

mongoose materialized plugin
59 stars 22 forks source link

Discriminator support #33

Open thowimmer opened 7 years ago

thowimmer commented 7 years ago

Hy everbody,

many thanks for the great work you did with this great mongoose plugin !

I want to store hierarchical data which uses mongoose schema inheritance by using Discriminators (http://mongoosejs.com/docs/discriminators.html)

By debugging I experienced that this is not working in version 0.1.9.

I prepared the following sample code:

var mongoose = require('mongoose');
var materializedPlugin = require('mongoose-materialized');
mongoose.connect('mongodb://localhost/test');

var Schema = mongoose.Schema;

//Scheme inheritance setup
var ShapeSchema = new Schema({
    name: String
}, {discriminatorKey: 'kind'});

ShapeSchema.plugin(materializedPlugin);

var Shape = mongoose.model('Shape', ShapeSchema);
var Circle = Shape.discriminator('Circle', new Schema({radius: Number}));
var Square = Shape.discriminator('Square', new Schema({side: Number}));

var rootShape = new Circle({radius: 5});
//var childShape = new Circle({radius: 5}); //-> THIS IS WORKING
var childShape = new Square({side: 5}); //-> NOT WORKING

rootShape.save(function (err) {
   if(err){
       console.log(err);
       return;
   }

   rootShape.appendChild(childShape, function (err) {
       if(err){
           console.log(err);
           return;
       }

       console.log("SUCCESS");
   });
});

If I append childs of the same type everything is working fine. However if I append childs of a different type (Circle -> Square in this example) I get Error: Parent not found!

As far as I saw using self.constructor (https://github.com/janez89/mongoose-materialized/blob/master/lib/materialized.js#L139) for the findOne(...) operation is causing this issue.

Therefore my suggestion to solve this issue would be to use the native mongodb collection instead:

self.collection.findOne(byId(self.parentId), addId({path: 1}), function (err, parent) {...}

Have you ever experienced this issue ?

Thanks for help