NodeJS sequelize和sqlite错误:无法读取未定义的属性'findAll'

时间:2018-07-03 06:22:02

标签: node.js sequelize.js

我正在学习如何使用NodeJS的简约Web框架来使用它。我还添加了ORM和sqlite的续集。 项目文件夹名称为expressapp,因此在根目录中,我使用sqlite创建了一个模型文件

models.js

const Sequelize = require("sequelize");

const db = new Sequelize({
  dialect: "sqlite",
  storage: "./db.sqlite"
});

const User = db.define("user", {
  username: { type: Sequelize.STRING },
  loggedIn: { type: Sequelize.BOOLEAN }
});

const Messages = db.define("messages", {
    public: { type: Sequelize.BOOLEAN },
    to: { type: Sequelize.STRING },
    messsage: { type: Sequelize.BOOLEAN },
    createdBy: { type: Sequelize.STRING },
    createdAt: { type: Sequelize.DATE }
})

db.sync();

module.exports = db;

在路由文件routes\index.js里面,我已经导入了模型,并尝试检查用户名是否存在(目前带有静态文本),然后再决定是否将用户名添加到列表中。

index.js

var express = require('express');
const models = require("./../models");

var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/login-ajax', function (req, res) {
  //assume the front end ensured there's valid post data
  let existing = models.user.findAll({
    where: {
        username: 'ME'
    }
  });

  res.send('Post data received')
})

module.exports = router;

在加载时,这是来自nodejs的终端上的消息,似乎表明一切正常。

[nodemon] restarting due to changes...
[nodemon] starting `node ./bin/www expressapp`
Tue, 03 Jul 2018 06:03:33 GMT sequelize deprecated String based operators are now deprecated. Please use Symbol based operators for better security, read more at http://docs.sequelizejs.com/manual/tutorial/querying.html#operators at node_modules\sequelize\lib\sequelize.js:242:13
Executing (default): CREATE TABLE IF NOT EXISTS `users` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `username` VARCHAR(255), `loggedIn` TINYINT(1), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);
Executing (default): PRAGMA INDEX_LIST(`users`)
Executing (default): CREATE TABLE IF NOT EXISTS `messages` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `public` TINYINT(1), `to` VARCHAR(255), `messsage` TINYINT(1), `createdBy` VARCHAR(255), `createdAt` DATETIME, `updatedAt` DATETIME NOT NULL);
Executing (default): PRAGMA INDEX_LIST(`messages`)

然后,我在浏览器的控制台上检查使用的发布请求是否存在错误

$.post("/login-ajax", function( data ) {
  console.log(data);
});

然后我得到错误Cannot read property 'findAll' of undefined和500响应错误。

2 个答案:

答案 0 :(得分:0)

找不到“ model.user”对象。您确定存在吗?这只是预感,但您可以检查一下。

答案 1 :(得分:0)

确定要正确导入模型吗?

如果您的项目结构如下:

root
- models.js
- routes
- - index.js

并且您想在index.js中导入models.js,那么您需要使用:

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

(或者至少尝试一下,因为在导入本地模块时您会在网络上找到不同的方法)

或者您只使用快速而肮脏的console.log(models);查看它是否正确导入,并查看它是否已定义

const models = require('./../models');
console.log(models);