Monday, 29 May 2017

Ssequelizejs, MySQL and passportjs user.findOne not a function

I'm currently migrating from mongodb to MySQL in my Node js application. I use sequelize as ORM, but I'm having some trouble migrating some passportjs code.

I have the following modal.

user.js:

"use strict";

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("users", {
    username: DataTypes.STRING,
    localemail: DataTypes.STRING,
    localpassword: DataTypes.STRING,
    facebookid: DataTypes.STRING,
    facebooktoken: DataTypes.STRING,
    facebookemail: DataTypes.STRING,
    facebookname: DataTypes.STRING,
    twitterid: DataTypes.STRING,
    twittertoken: DataTypes.STRING,
    twitterdisplayname: DataTypes.STRING,
    twitterusername: DataTypes.STRING,
    googleid: DataTypes.STRING,
    googletoken: DataTypes.STRING,
    googleemail: DataTypes.STRING,
    googlename: DataTypes.STRING
  });

  return User;
};

And the following function in my passportjs file:

...

// load all the things we need
var LocalStrategy    = require('passport-local').Strategy;
var FacebookStrategy = require('passport-facebook').Strategy;
var TwitterStrategy  = require('passport-twitter').Strategy;
var GoogleStrategy   = require('passport-google-oauth').OAuth2Strategy;

// load up the user model
var User       = require('../models/user');

...

passport.use('local-login', new LocalStrategy({
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true 
    },
    function(req, email, password, done) {
        if (email)
            email = email.toLowerCase(); 
    // asynchronous
    process.nextTick(function() {
        User.findOne({
            where: {
                localemail: email
            }
        }).then(function(user) {
            // if there are any errors, return the error
            if (err)
                return done(err);

            // if no user is found, return the message
            if (!user)
                return done(null, false, req.flash('loginMessage', 'No user found.'));

            if (!validPassword(password))
                return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));

            // all is well, return user
            else
                return done(null, user);
        });
    });

}));

...

The applications exits with the following error:

passport.js:100
                    User.findOne({
                         ^

TypeError: User.findOne is not a function

I have looked at this code on github for inspiration:

https://github.com/sequelize/express-example

Any ideas to what i'm overlooking?



via Tony

No comments:

Post a Comment