Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get name of model/collection in mongoose pre save hook

I am creating a mongoose pre save hook, I want to know the name of the model/collection, which I am saving in the pre save hook. From which variable can I get it.

module.exports = exports = function lastModifiedPlugin (schema, options) {
    schema.pre('save', function (next) {
        var self = this;

        self.constructor.findOne({ _id: self._id }, function (err, launch){
            console.log(" model " + self.mongooseCollection);
            console.log(Object.getOwnPropertyNames(this));
            console.log(Object.getOwnPropertyNames(schema));

            next()
        });

    })

    if (options && options.index) {
        schema.path('lastMod').index(options.index)
    }
}

I tried to explore functions and properties of this and schema variable but could not got the name od model being saved.

like image 487
Saurabh Avatar asked Jan 07 '16 13:01

Saurabh


1 Answers

We can get it from:

self.constructor.modelName

like image 113
Saurabh Avatar answered Sep 19 '22 03:09

Saurabh