简体   繁体   English

无法读取未定义的 sequelize express JS 的属性“findAll”

[英]Cannot read property 'findAll' of undefined sequelize express JS

I have a problem with my code when using sequelize auto.使用sequelize auto 时我的代码有问题。 the problem is how to connect sequelize model to database setting on DB.js , so that we can using findall function or any else问题是如何连接sequelize模型数据库设置DB.js ,这样我们就可以使用findall功能或其他任何

Model :模型 :

/* jshint indent: 2 */
const db = require('../../db/database')
const sequelize = db.sequelize

module.exports = function(sequelize, DataTypes) {
  cust: sequelize.define('ms_customer', {
    id: {
      type: DataTypes.CHAR(10),
      allowNull: false,
      primaryKey: true
    },
    gender_id: {
      type: DataTypes.INTEGER(1),
      allowNull: true
    },
    status: {
      type: DataTypes.CHAR(1),
      allowNull: true
    }
  }, {
    tableName: 'ms_customer'
  });
};

DB.js connection : DB.js 连接:

const Sequelize = require('sequelize')

const sqlz = new Sequelize('db', 'user', 'pass', {
    host: 'localhost',
    dialect: 'mysql',
    pool: {
        max: 5,
        min: 10,
        idle: 10000
    }
}) 

sqlz
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });

module.exports = {
    sqlz: sqlz,
    Sequelize: Sequelize
}

Query :询问 :

const customerModel = require('../../db/model/ms_customer')
const cust = customerModel.cust

module.exports = {
    modelGetCustomerById : (param,req,res) => {
            cust.findAll({
                where: {
                    id: {
                        param
                    }
                }
            }).then(customer => {
                // console.log(customer)
                res.json(customer)
            })
    }
}

Controller :控制器 :

 const customer = require('../../db/query/customer')
    const sequelize = require('sequelize')

    module.exports = {
        getCustomerById: async(req,res) => {
            var customerId = req.params.id
            let getCustomerId = await customer.modelGetCustomerById(customerId) 
            // console.log(getCustomerId)
            if(!getCustomerId){
                return res.status(500).json({status: "Failed", message:"User not found"});
            }
            return res.status(200).json({status: "Success", message:getCustomerId});
        }
    }

why i always got error为什么我总是出错

Cannot read property 'findAll' of undefined无法读取未定义的属性“findAll”

please help..请帮忙..

I've running code without error on my project that remodel by sequelize-auto and connect by sequelize.我在我的项目中运行了没有错误的代码,这些代码通过 sequelize-auto 进行改造并通过 sequelize 连接。 Check it out :一探究竟 :

on models/index.js: ( for connection to db )在模型/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 = {};

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);
}

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;

On models/m_bank.js code :在模型/m_bank.js 代码上:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('m_bank', {
    bank: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: '',
      primaryKey: true
    },
    bank_name: {
      type: DataTypes.STRING,
      allowNull: true
    },
    address: {
      type: DataTypes.STRING,
      allowNull: true
    },
    branch: {
      type: DataTypes.STRING,
      allowNull: true
    },
    create_date: {
      type: DataTypes.DATE,
      allowNull: true
    },
    update_date: {
      type: DataTypes.DATE,
      allowNull: true
    }
  }, {
    tableName: 'm_bank',
    timestamps: false,
    schema: 'db_hrms'
  });
};

on controllers/m_bank.js在控制器/m_bank.js 上

const M_Bank = require('../models').m_bank;

module.exports = {
  list(req, res) {
    return M_Bank
      .findAll()
      .then(M_Bank => res.status(200).send(M_Bank))
      .catch((error) => {
        console.log(error.toString());
        res.status(400).send(error)
      });
  },

  getById(req, res) {
    return M_Bank
      .findById(req.params.id)
      .then(M_Bank => {
        if (!M_Bank) {
          return res.status(404).send({ message: "M_Bank Not Found" });
        }
        return res.status(200).send(M_Bank);
      })
      .catch((error) => res.status(400).send(error));
  },

  add(req, res) {
    return M_Bank
      .findOrCreate({
        where: { bank: req.body.bank },
        defaults: {
          bank: req.body.bank,
          bank_name: req.body.bank_name,
          address: req.body.address,
          branch: req.body.branch
        }
      })
      .spread((M_Bank, created) => {
        return res.status(created === false ? 400 : 200).send({
          messsage: "Bank record " + (created === false ? "Already exists" : "successfully added")
        })
      })
      // .then((M_Bank) => { res.status(201).send(M_Bank) })
      // .catch((error) => res.status(400).send(error));
  },

  update(req, res) {
    return M_Bank
      .findById(req.params.id)
      .then(M_Bank => {
        if (!M_Bank) {
          return res.status(404).send({ message: "Bank Not Found" });
        }
        return M_Bank
          .update({
            bank: req.body.bank || M_Bank.bank,
            bank_name: req.body.bank_name || M_Bank.bank_name,
            address: req.body.address || M_Bank.address,
            branch: req.body.branch || M_Bank.branch
          })
          .then(() => res.status(200).send({
            message: "Bank successfully update"
          }))
          .catch((error) => res.status(400).send({
            message: "Bank Not Found"
          }));
      })
      .catch((error) => res.status(400).send({
        message: "No parameter for Bank ID"
      }));
  },

  delete(req, res) {
    return M_Bank
      .findById(req.params.id)
      .then((M_Bank) => {
        if (!M_Bank) {
          return res.status(404).send({ message: "M_Bank Not Found" });
        }
        return M_Bank
          .destroy()
          .then(() => res.status(204).send({
            message: "Bank record successfully delete"
          }))
          .catch((error) => res.status(400).send({
            message: "Bank Not Found"
          }));
      })
      .catch((error) => res.status(400).send(error));

  }
}

on config/config.json configuration code:关于 config/config.json 配置代码:

{
  "development": {
    "username": "tihagi",
    "password": "123456",
    "database": "db_tihagi",
    "host": "127.0.0.1",
    "dialect": "postgres"
  },
  "test": {
    "username": "tihagi",
    "password": "123456",
    "database": "db_tihagi",
    "host": "127.0.0.1",
    "dialect": "postgres"
  },
  "production": {
    "username": "tihagi",
    "password": "123456",
    "database": "db_tihagi",
    "host": "127.0.0.1",
    "dialect": "postgres"
  }
}

Hope this can help you.希望这可以帮到你。

Note: my db is postgres, please change as per your dialect db.注意:我的数据库是 postgres,请根据您的方言数据库更改。

-Tihagi -蒂哈吉

Possible reason could be that you didn't pass the model name correctly.可能的原因可能是您没有正确传递模型名称。 What is the output of console.log(cust) console.log(cust)的输出是什么

Change your customer model to this one.将您的客户模型更改为这种模型。

/* jshint indent: 2 */
const db = require('../../db/database')
const sequelize = db.sequelize

module.exports = function(sequelize, DataTypes) {

  var cust = sequelize.define('ms_customer', {
    id: {
      type: DataTypes.CHAR(10),
      allowNull: false,
      primaryKey: true
    },
    gender_id: {
      type: DataTypes.INTEGER(1),
      allowNull: true
    },
    status: {
       type: DataTypes.CHAR(1),
       allowNull: true
    }
  }, {
    tableName: 'ms_customer'
  });

 return cust;
};

Your query to您的查询

const customerModel = require('../../db/model/ms_customer')
//const cust = customerModel.cust .... you do not need this.

module.exports = {
    modelGetCustomerById : (param,req,res) => {
         customerModel.findAll({
             where: {
                 id: {
                     param
                 }
             }
         }).then(customer => {
             // console.log(customer)
             res.json(customer)
         })
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Sequelize.js/Node.js/Express.js:Tasks.findAll() 返回一个 TypeError:Cannot read property 'findAll' of undefined - Sequelize.js/Node.js/Express.js: Tasks.findAll()returns a TypeError:Cannot read property 'findAll' of undefined 无法读取 undefined sequelize express JS 的属性“findAll”并且 req.body 是一个空对象 - Cannot read property 'findAll' of undefined sequelize express JS and req.body is an empty object Sequelize,Express JS - 无法读取未定义的属性(读取“findAll”) - Sequelize, Express JS - Cannot read properties of undefined (reading 'findAll') 无法读取节点/express JS 中未定义的属性 FindAll(),现有 mySQL DB - cannot read property FindAll() of undefined in node/express JS, existing mySQL DB 无法读取未定义的属性'findAll' - Cannot read property 'findAll' of undefined Node.js和mongodb:TypeError:无法读取未定义的属性'findAll' - Node.js and mongodb: TypeError: Cannot read property 'findAll' of undefined 类型错误:无法读取未定义的属性“findAll” - Node.js + Postgresql - TypeError: Cannot read property 'findAll' of undefined - Node.js + Postgresql 无法读取 Express js 中未定义的属性“状态” - Cannot read property 'status' of undefined in Express js 无法读取 Sequelize 节点 js 中未定义的属性“创建”错误 - Cannot read property 'create' of undefined” error in Sequelize node js 类型错误:无法读取未定义的属性“findAll” - TypeError: Cannot read property 'findAll' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM