Mongoose: Is it possible to load a plugin after model definition?

Created on 22 Jul 2014  路  4Comments  路  Source: Automattic/mongoose

All 4 comments

Yes! Close de issure

So how do I do that?

This unit test does not pass:

var mongoose = require("mongoose");

var chai = require("chai");
chai.should();

describe("Mongoose plugin load", function() {
    beforeEach(function() {
        var schema = new mongoose.Schema({});

        schema.plugin(function(schema, options) {
            schema.statics.foobar = function() {
                return 1;
            };
        });

        mongoose.model("Foo", schema);
    });

    beforeEach(function() {
        var Foo = mongoose.model("Foo");

        Foo.schema.plugin(function(schema, options) {
            schema.statics.bar = function() {
                return 2;
            };
        });
    });

    it("should be loadable after model definition", function() {
        var Foo = mongoose.model("Foo");

        Foo.foobar().should.equal(1); // success!!

        Foo.bar().should.be.equal(2); // error!!
        // Object function model... has no method 'bar'
    });
});

Once a model is compiled, changing the schema in any way, including plugins, isn't supported right now.

Thanks. I will export schemas instead of models, so they can be changed before use.

Was this page helpful?
0 / 5 - 0 ratings