Tuesday 11 April 2017

Mongoose model as an ES6 class with inheritance chain

I was trying to create a ES6 class hierarchy to implement a caching layer between mongoose and mongodb queries. I saw this PR https://github.com/Automattic/mongoose/pull/4668 and based on that wrote the below code.

'use strict'

const mongoose = require('mongoose');
mongoose.connect("mongodb://host:port/db", {});
mongoose.connection.on('error', console.error.bind(console, 'DB connection failed', arguments));
mongoose.connection.once('open', console.log.bind(console, 'Connected to DB'));

class Base extends mongoose.Model {
    save() {
        console.log('Base class save()')
        return super.save();
    }

    findOne(query){
        console.log('Base class find...');
        return super.findOne(query);
    }
}

class Derived extends Base{
    save(){
        console.log('Derived class save()');
        super.save();
    }

    static getOne(){
        console.log('Derived class Get one');
        return this.findOne({});
    }
}

let usersSchema = new mongoose.Schema({ name: String })

usersSchema.loadClass(Derived);

let User = mongoose.model(Derived, usersSchema, 'users');

setTimeout(function(){
    User.getOne()
            .then(user => console.log('Found user...', user));

    let newUser = new User();
    console.log('newUser instance of Derived ? ', (newUser instanceof Derived));
    console.log('newUser instance of Base ? ', (newUser instanceof Base));
    newUser.name = 'Tony';
    newUser.save()
                .then(result => console.log('Saved', result));
}, 2000);

Since the methods are overridden in the derived class, I was expecting the calls to the methods in Derived class will in turn call the Base class and then I could add additional logic in Base class before / after queries.

Below is the output which I getting, which indicates that the method invocations are not hitting the Derived class.

Output

Connected to DB
Derived class Get one
newUser instance of Derived ?  true
newUser instance of Base ?  true
Base class save()
Found user... { _id: 58ec765f9dd99f049c2a833b, name: 'Tony', __v: 0 }

When I call the save method, it does not hit the Base class when I call the getOne static method in Derived class. I am not sure where am I going wrong. Can anyone throw some light on this.



via Tony

No comments:

Post a Comment