Mongoose static function that uses .find() returns query and static function is not a recognized

Viewed 1003

so i have declared a schema and provided a static function to it that search for a user by Email in the file below :

./database.js

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/investDB', { useNewUrlParser: true })

const Schema = mongoose.Schema

var UserSchema = new Schema({
  email: String,
  username: String,
  password: String,
  firstName: String,
  lastName: String
})

UserSchema.statics.findByEmail = function (email) {
      return this.find({email: email })
}

var User = mongoose.model('User', UserSchema)
module.exports = User

and called after by an other file

./fonctions.js

var mongooseModel = require('./database')

function loginAlreadyExist(emailInput) {
  var onDataBase = new mongooseModel()
  return onDataBase.findByEmail(emailInput)
}

exports.loginAlreadyExist = loginAlreadyExist

after useing the static function i get the following Error

onDataBase.findByEmail is not a function

after that i decided to see what the findByEmail returns in the first place so i added console.log(User.findByEmail("a@a")) just before the ./database.js file export.

while i'm expecting an output similar to the schema defined i get a query instade that doesn't contain any of the information even if the mail existe

Query {
  _mongooseOptions: {},
  _transforms: [],
  mongooseCollection: 
   NativeCollection {
     collection: null,
     opts: 
      { bufferCommands: true,
        capped: false,
        '$wasForceClosed': undefined },
     name: 'users',
     collectionName: 'users',
     conn: 
      NativeConnection {
        base: [Object],

....
options: {},
  _conditions: { email: 'a@a' },
  _fields: undefined,
  _update: undefined,
  _path: undefined,
  _distinct: undefined,
  _collection: 
   NodeCollection {
     collection: 
      ....
     collectionName: 'users' },
  _traceFunction: undefined,
  '$useProjection': true }

so her i'm in front of 2 problems,

1) why the static fonction is not recognized 2) why is the findByEmail output doesn't respect the schema (or the collection structured in mongodb)

2 Answers

There is a bracket missing:

UserSchema.statics.findByEmail = function (email) {
    return this.find({email: email })
}

Also you get the result of the query in a callback function on find():

UserSchema.statics.findByEmail = function (email) {
    let data;
    this.find({email: email }, function (err, result) {
        if (err) throw err;
        data = result;
    }
    return data;
}

In your model

UserSchema.statics.findByEmail = function (email) {
    return new Promise((resolve, reject) => {
        return this.findOne({ email: email }).exec(function (err, user) {
            if (err) reject(err)
            resolve(user);
        });
    });
}

Related