Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - this.find() does not exist

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?

like image 302
SWAGN Avatar asked Jul 06 '16 16:07

SWAGN


1 Answers

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

like image 109
JohnnyHK Avatar answered Oct 20 '22 10:10

JohnnyHK