within my model, I am trying to do a static getUserByToken method. However, if I do it like in the documentation, I am getting
this.find is not a function
My code looks like this:
'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|[a-z][a-z])|([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 am guessing it is just a simple mistake, however, I can not compile the model and than add the static function to the schema/model as this is done through an init function at startup, that compiles all the models.
Anybody can help me with that?
You need to use a normal function declaration for your static function instead of using the fat-arrow syntax so that you preserve Mongoose's meaning of this
within the function:
schema.statics.getUserByToken = function(token, cb) {
return this.find({ examplefield: token }, cb);
};
Reference: https://mongoosejs.com/docs/guide.html#statics
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With