【问题标题】:Cannot read property 'findAll' of undefined sequelize无法读取未定义续集的属性“findAll”
【发布时间】:2019-06-19 20:06:47
【问题描述】:

我是一个新的学习者来表达js和sequelizejs。我成功迁移了我的数据库中的表,所以我猜连接很好。

这是我的代码。 https://github.com/Picks42/express-test 请查看此文件 https://github.com/Picks42/express-test/blob/master/models/user.js

然后查看这个 https://github.com/Picks42/express-test/blob/master/controller/test.js

让我知道是什么问题。

【问题讨论】:

  • 我认为这很明显,因为我也看不到模型,它正在尝试 models.user.findAll,你也定义了变量 M_Bank。还是你输入错了?

标签: mysql node.js express sequelize.js


【解决方案1】:
// all the models using your index.js loader
const models = require('../models');
// the user model, note the capital User since 
const M_Bank = models.User;

exports.getTest = function(req,res){
    return M_Bank
    .findAll()
    // don't use M_Bank here since you are getting an array of Instances of the Model
    .then(users => res.status(200).send(users))
    .catch((error) => {
      console.log(error.toString());
      res.status(400).send(error)
    });

    /* this will never execute because it is after the return
    exports.index = function (request, response, next) {
        response.json((M_Bank.findAll()));
    };
    */
};

如果您可以选择使用async/await,它会使代码更具可读性。

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

exports.getTest = async function(req, res) {
  try {
    const users = await M_Bank.findAll();
    return res.status(200).send(users);
  } catch (err) {
    console.log(err.toString());
    return res.status(400).send(err);
  }
};

【讨论】:

    【解决方案2】:

    您应该去掉第 3 行中的 .User 字段。因为您已经从 models/user 文件中导出了 User 本身。 另外,我建议您不要乱用变量名称。 M_Bank 变量不会自己说话

    
    const M_Bank = require('../models/user');
    exports.getTest = function(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)
        });
        exports.index = function (request, response, next) {
            response.json((M_Bank.findAll()));
        };
    };
    

    【讨论】:

    • 如果我使用你所说的,它会给我这个错误prntscr.com/o46h7y更新代码prntscr.com/o46hdr
    • 另外,当我用我的代码调试时,如果发现这个prntscr.com/o46ixr
    • require 这里返回的是卸载的模型定义,一旦加载到 Sequelize 中,您必须通过 index.js 加载器获取它 - const M_Bank = require('../models').User;
    猜你喜欢
    • 2020-01-23
    • 2019-04-12
    • 1970-01-01
    • 2016-09-07
    • 2016-04-20
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    相关资源
    最近更新 更多