Express Sequelize错误-无法读取未定义的属性'findAll'

罗卡

我通过使用Sequelize的github示例进行了一些更改,成功连接了Sequelize和Express。我现在正在尝试做一个简单的Sequelize查询来测试连接,但是继续收到一条错误消息,指出未定义我查询的模型。

// ./models/index.js
...
const sequelize = new Sequelize(process.env.DB, process.env.DB_USER, process.env.DB_PASS, {
  host: 'localhost',
  dialect: 'postgres'
});
// Test SEQUELIZE connection
sequelize
  .authenticate()
  .then(() => {
    console.log('Database connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    var 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;
// ./routes/index.js
const models = require('../models');
const express = require('express');
const router = express.Router();

router.get('/contacts', (req, res) => {
    models.Contact.findAll().then(contacts => {
        console.log("All users:", JSON.stringify(contacts, null, 4));
    });
});


module.exports = router;
// ./models/contact.js
const Sequelize = require('sequelize');
var Model = Sequelize.Model;

module.exports = (sequelize, DataTypes) => {
    class Contact extends Model {}
    Contact.init({
      // attributes
      firstName: {
        type: Sequelize.STRING,
        allowNull: false
      },
      lastName: {
        type: Sequelize.STRING,
        allowNull: false
      }
    }, {
      sequelize,
      modelName: 'contact'
      // options
    });
    return Contact;
};

使用邮差打/contactsGET请求时遇到的错误是:

[nodemon] starting `node server.js`
The server is now running on port 3000!
Executing (default): SELECT 1+1 AS result
Database connection has been established successfully.
TypeError: Cannot read property 'findAll' of undefined
    at router.get (C:\Users\username\desktop\metropolis\metropolis-backend\routes\index.js:6:20)
纳尔·列维(Naor Levi)

您没有正确要求模型。./routes/index.js添加下一行:

const Contact = require('./models/contact.js');

然后打电话 Contact.findAll()...

第二种方法:

您可以通过将所有模型导入到loader.js文件中来收集所有模型,该文件将存储在models目录中。该模块的整个工作是将模块一起导入到同一位置,然后从一个位置导出它们。它看起来像这样:

// loader.js
const modelA = require('./modelA');
const modelB = require('./modelB');
const modelC = require('./modelC');
...

module.exports = {
 modelA,
 modelB,
 modelC,
 ...
}

然后您可以通过以下方式要求它:

router/index.js

const Models = require('./models');
const contact = Models.Contact;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Sequelize-无法读取未定义的属性“ define”

express multer无法读取未定义的属性“ profileimage”

Sequelize关联错误无法读取未定义的属性“ getTableName”

Sequelize DataTypes TypeError:无法读取未定义的属性“ INTEGER”

Express.js无法读取未定义的属性“ req”

NodeJS Sequelize-无法读取未定义的属性'_isSequelizeMethod'

无法读取未定义的属性“ destroy”-Express JS Session

Express JS:无法读取未定义的属性“ lazyrouter”

TypeError:无法读取未定义的React Express的属性'prototype'

Sequelize.js / Node.js / Express.js:Tasks.findAll()返回TypeError:无法读取未定义的属性'findAll'

无法读取未定义的Express API的属性“ count”

TypeError:无法读取未定义Express的属性“使用”

express-openapi-validator:错误:TypeError:无法读取未定义的属性“模式”

express :: server :: routerTypeError:无法读取未定义的属性“ length”

TypeError:无法读取未定义的属性“ findAll”(mariaDB,ExpressJs)

TypeError:无法读取未定义的属性'findAll'

无法在Express 4的错误处理程序中读取未定义的属性'domain'

Ember 数据 findAll() 导致“类型错误:无法读取未定义的属性‘类型’”

类型错误:无法读取未定义的属性“indexOf”,无法读取未定义的属性“toLowerCase”

类型错误:无法读取 express、postgres、sequelize 中未定义错误的属性“create”

Express:无法读取未定义的属性“forEach”

无法读取未定义的属性“on”?-> 错误

类型错误:无法读取 Express 上未定义的属性“get”

Sequelize 创建错误:无法读取未定义的属性“长度”

nodeJS/Express TypeError:无法读取未定义的属性“方法”

SEQUELIZE:“无法读取未定义的属性‘长度’”

类型错误:无法读取 node.JS 中未定义的属性“用户名”/express 无法发布到路由

Sequelize 迁移:错误:无法读取未定义的属性“toString”

Express.js 应用程序错误:无法读取未定义的属性(读取 'transfer-encoding'