Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register mongoose plugin for all schemas?

What am I missing? The Mongoose docs say that mongoose.plugin() registers a plugin for all schemas. This is not working. I CAN register my plugin on EACH schema.

My plugin:

module.exports = function (schema, options) {

    schema.set('toObject',{
        transform: function (doc, ret, options) {
            return {
                test: 'It worked!'
            };
        }
    });
};

My schema:

var testPlugin = require('test-plugin.js');

var personSchema = mongoose.Schema({

    _id : { type: String, default: $.uuid.init },

    ssn : { type: String, required: true, trim: true },

    first : { type: String, required: true, trim: true },
    middle : { type: String, required: true, trim: true },
    last : { type: String, required: true, trim: true }
});
personSchema.plugin(testPlugin);

var model = mongoose.model('Person', personSchema);

module.exports = model;

The code above works, unfortunately. However, the following code does not:

var personSchema = mongoose.Schema({

    _id : { type: String, default: $.uuid.init },

    ssn : { type: String, required: true, trim: true },

    first : { type: String, required: true, trim: true },
    middle : { type: String, required: true, trim: true },
    last : { type: String, required: true, trim: true }
});

var model = mongoose.model('Person', personSchema);

module.exports = model;

My test app:

var testPlugin = require('test-plugin.js');
mongoose.plugin(testPlugin);

mongoose.Promise = global.Promise;
mongoose.connect(config.db);
mongoose.connection.on('error', function (err) {
    if (err) { throw err; }
});
mongoose.connection.once('open', function (err) {
    if (err) { throw err; }

    seeds.doSeed(function(err){
        if (err) { return process.exit(1); }

        models.Person.find({}, function(err, people){
            if (err) { throw err; }

            var person = people[0];
            var oPerson = person.toObject();

            console.log(JSON.stringify(oPerson));
        });
    });
});

I've tried moving the mongoose.plugin(testPlugin) all over the app.js file... after the connect, etc... and nothing has worked.

like image 964
G. Deward Avatar asked Aug 17 '16 15:08

G. Deward


People also ask

Do you need a schema for Mongoose?

With Mongoose, you would define a Schema object in your application code that maps to a collection in your MongoDB database. The Schema object defines the structure of the documents in your collection. Then, you need to create a Model object out of the schema. The model is used to interact with the collection.

Which schema types are not supported by Mongoose?

Mongoose does not natively support long and double datatypes for example, although MongoDB does.

What is plugin in Mongoose?

Plugins are a tool for reusing logic in multiple schemas. Suppose you have several models in your database and want to add a loadedAt property to each one. Just create a plugin once and apply it to each Schema : // loadedAt. js module.


2 Answers

Plugins might not be registered with mongoose.plugin(myMongoosePlugin) because mongoose models were created before you are registering plugins globally.

  • In case if you have expressjs routes:

Make sure that in your app.js (server.js) you are registering mongoose plugins before you are registering/creating expressjs routes (which are using mongoose models to communicate with database).

Example:

in app.js

const express = require(express);
const mongoose = require('mongoose');
const myMongoosePlugin = require('<Mongoose Plugin file path>');

mongoose.plugin(myMongoosePlugin);

let app = express();

//register expressjs routes
require('<Express routes file path>')(app, express.Router());

// or create expressjs routes
app.post('/person', (req, res, next) => {
    //where someMethod is using person mongoose model
    this.someController.someMethod(someArguments)
        .then((user) => {
            res.json(user);
        }).catch((error) => {
            next(error);
        });
});

// ... Some other code ...
mongoose.connect(<databaseConnectionString>);
app.listen(<Port>);
like image 162
Andrei Surzhan Avatar answered Nov 15 '22 17:11

Andrei Surzhan


Try requiring your model also in your app.js file. Somewhere after mongoose.plugin(testPlugin).

like image 23
Petar Avatar answered Nov 15 '22 18:11

Petar