Reaching model static methods inside middleware.

63 views
Skip to first unread message

Amir Abu Shareb

unread,
May 9, 2013, 8:43:12 AM5/9/13
to mongoo...@googlegroups.com
I have a case where each `Customer` `uid, code, companyId` must be unique for each customer,
the only way i can check is via middleware in a pre('save').

But i can't reach the model `.findOne()` or `.count()` or any query methods..

Is there a way to do this ?

Aaron Heckmann

unread,
May 9, 2013, 9:59:07 AM5/9/13
to mongoo...@googlegroups.com
this.constructor should work. 
--
Documentation - http://mongoosejs.com/
Plugins - http://plugins.mongoosejs.com/
Bug Reports - http://github.com/learnboost/mongoose
Production Examples - http://mongoosejs.tumblr.com/
StackOverflow - http://stackoverflow.com/questions/tagged/mongoose
Google Groups - https://groups.google.com/forum/?fromgroups#!forum/mongoose-orm
Twitter - https://twitter.com/mongoosejs
IRC - #mongoosejs
---
You received this message because you are subscribed to the Google Groups "Mongoose Node.JS ODM" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongoose-orm...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 


--
Aaron



Andrew Morton

unread,
Mar 24, 2015, 3:23:52 AM3/24/15
to mongoo...@googlegroups.com
Any chance of a working example to the original question? I'm trying to trigger statics function inside middleware

PushSchema.statics.doStuff = function(id, cb){

    this.findOne({_id:id}, function(err, push){
        
        // Can't get to this point becauase Pre Fails

    });

}


PushSchema.pre('save', function (next) {


    // this.doStuff(10); // Fails
    // this.statics.doStuff(10); // Fails
    // PushSchema.statics.doStuff(10); // Fails
    // this.doStuff(10); // Fails

    next();
});

Robert Schütz

unread,
Mar 24, 2015, 5:33:29 PM3/24/15
to mongoo...@googlegroups.com
As Aaron pointed out, use 
PushSchema.pre('save', function (next) {
  this.constructor.doStuff(10);
  next();
});

Altenatively, use this ('whatever' should of course be your model name):
PushSchema.pre('save', function (next) {
  mongoose.model('whatever').doStuff(10);
  next();
});
Reply all
Reply to author
Forward
0 new messages