Mongoose - this.find () does not exist

in my model, I am trying to make the static method getUserByToken. However, if I do this as in the documentation, I get

this.find is not a function 

My code is as follows:

 'use strict'; const mongoose = require('mongoose'); const Schema = mongoose.Schema; const schema = new Schema({ mail: { type: String, required: true, validate: { validator: (mail) => { return /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[az][az])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i.test(mail); } } }, birthDate: { type: Date, required: true, max: Date.now, min: new Date('1896-06-30') }, password: { type: String, required: true }, ... }); schema.statics.getUserByToken = (token, cb) => { return this.find({ examplefield: token }, cb); }; module.exports.Schema = schema; 

I suppose this is just a simple mistake, however I cannot compile the model and not add a static function to the schema / model, as this is done through the init function at startup, which compiles all the models.

Can anybody help me?

+5
source share
1 answer

You need to use a normal function declaration for your static function instead of using the thick arrow syntax so that you keep the Mongoose this value inside the function:

 schema.statics.getUserByToken = function(token, cb) { return this.find({ examplefield: token }, cb); }; 
+4
source

All Articles