TypeError:无法从sequelize模型中读取未定义的属性“find”

时间:2016-11-20 18:04:13

标签: node.js express sequelize.js

我正在尝试使用sequelize在我的数据库中查找记录,但我得到了这个:

.find({ where: { name: email } })
TypeError: Cannot read property 'find' of undefined

这是我的models / index.js

var Sequelize = require('sequelize')
  , sequelize = new Sequelize(process.env.MYSQL_DB, process.env.MYSQL_USER, process.env.MYSQL_PASSWORD, {
      dialect: "mysql", // or 'sqlite', 'postgres', 'mariadb'
      port:    3306, // or 5432 (for postgres)
});

// load models                 
var models = [                 
  'user',            
];

models.forEach(function(model) {
  module.exports[model] = sequelize.import(__dirname + '/' + model);
});

这是我的models / user.js

var Sequelize = require("sequelize");

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("User", {
    email: DataTypes.STRING,
    password: DataTypes.STRING,
    token: DataTypes.STRING
  }, {
    tableName: 'users'
  }

  );

  return User;
};

这就是我在我的文件中导入用户模型的方式:

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

修改

我正在尝试使用User来创建本地护照注册。 我在config / passport.js中调用User

var LocalStrategy = require('passport-local').Strategy;
var SlackStrategy = require('passport-slack').Strategy;
var User  = require('../models').User;
var mysql = require('mysql');
var connection = mysql.createConnection({
  host     : process.env.MYSQL_HOST,
  user     : process.env.MYSQL_USER,
  password : process.env.MYSQL_PASSWORD,
  database : process.env.MYSQL_DB
});

module.exports = function(passport) {
    // used to serialize the user for the session
    passport.serializeUser(function(user, done) {
        console.log("abc serializeUser");
        console.log(user);
        done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
        console.log("abc deserializeUser");
        User.findById(id).then(function(user){
            done(null, user);
        }).catch(function(e){
            done(e, false);
        });
    });

    passport.use('local-signup', new LocalStrategy(
        {
            // by default, local strategy uses username and password, we will override with email
            usernameField : 'name',
            passwordField : 'password',
            passReqToCallback : true // allows us to pass back the entire request to the callback
        },

        function(req, email, password, done) 
        {

            process.nextTick(function() {

                User
                    .find({ where: { name: email } })
                    .then(function(err, user) {
                        if (!user) {
                          console.log('No user with the username "john-doe" has been found.');
                        } else {
                          console.log('Hello ' + user.name + '!');
                          console.log('All attributes of john:', user.get());
                        }
                    });


        }           
    ));


    passport.use('slack', new SlackStrategy({
        clientID: process.env.SLACK_ID,
        clientSecret: process.env.SLACK_SECRET,
        scope: "users:write"
    },
        function(accessToken, refreshToken, profile, done) {
            User.findOrCreate({ SlackId: profile.id }, function (err, user) {
              return done(err, user);
            });
        }
    ));

};

2 个答案:

答案 0 :(得分:2)

你应该在User续集方法之后得到你的import模型。

所以在你的情况下你应该这样做:

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

这应该有用。

答案 1 :(得分:1)

您可以在一个文件中定义/初始化模型及其关系,但是可以在单独的模型文件中描述模型。

index.ts

import { TableNames } from '../constants';
import { groupAttributes, GroupModel, groupOptions } from './group.model';
import { userAttributes, UserModel, userModelOptions } from './user.model';

GroupModel.init(groupAttributes, groupOptions);
UserModel.init(userAttributes, userModelOptions);

GroupModel.belongsToMany(UserModel, { through: TableNames.USER_GROUPS });
UserModel.belongsToMany(GroupModel, { through: TableNames.USER_GROUPS });

所有模型详细信息,例如groupAttributesgroupOptions都放入另一个文件中:

group.model.ts

import { DataTypes, Model } from 'sequelize';
import { TableNames } from '../constants';
import { sequelizeConnection } from '../connection';
import { GroupPermission } from '../../entities/group';

export class GroupModel extends Model {
  public id!: string;
  public name!: string;
  public permissions!: GroupPermission[];
}

export const groupAttributes = {
  id: {
    type: DataTypes.UUID,
    primaryKey: true,
  },
  name: {
    type: new DataTypes.STRING(255),
    allowNull: false,
  },
  permissions: {
    type: DataTypes.ARRAY(DataTypes.STRING),
    allowNull: true,
  },
};

export const groupOptions = {
  tableName: TableNames.GROUPS,
  sequelize: sequelizeConnection,
  freezeTableName: true,
  timestamps: false,
  modelName: 'Group',
};

关键是要在设置关系的同一文件中init个模型