cphill
cphill

Reputation: 5914

TypeError models.User.find is not a function

I am running into a strange bug with my code where my .find() method throws a TypeError, but when I run .findAll() I have no issues. My application is using the skeleton setup from the sequelize-cli tool and I'm not sure if the issue has to do with that setup, but I would rather use .find() since I want to return a single record rather than .findAll() for all scenarios.

Error:

TypeError: models.User.find is not a function

Query:

var models  = require('./models');

passport.deserializeUser(function(id, done) {
  console.log(`deserializeUser ${id}`) //Returns proper value
    models.User.find({
        where: {
            id: id
        }
    }).then(function(user){
        console.log(`users test: ${JSON.stringify(user)}`)
        console.log("User ID: " + user[0].userId + " is deserializing");
        done(null, user);
    }).error(function(err) {
        done(err, null);
    });
});

user.js:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    email: DataTypes.STRING,
    google_id: {
      type: DataTypes.INTEGER,
      field: 'google_id'
    }
  }, {});
  User.associate = function(models) {
    // associations can be defined here
  };
  return User;
};

index.js:

'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

// Set DB Connection
let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

// Import model files in models folder and make table associations where present
fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    const model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

Upvotes: 1

Views: 877

Answers (1)

A. Granados
A. Granados

Reputation: 131

what version of sequelize are you using? .find() was removed on sequelize V5. instead of using .find() you can use findOne() if you want to fetch a single instance from database and if you want to find some element in the database by primary key, use .findByPk(). for example:

models.User.find({ where: { id: id } })

could be : models.User.findByPk(id)

.find() method only works on sequelize before V5.

check docs for more information:

http://docs.sequelizejs.com/manual/upgrade-to-v5.html

Upvotes: 1

Related Questions