简体   繁体   中英

Sequelize sqlite3 connects to database but throw error when fetching data

I'm using sequelize with sqlite3 inside nodejs.

The connection to database file runs fine with no error, but when trying to access it for the first time I'm getting the following error (no matter what table or query I try to do):

TypeError: Cannot read property 'findOne' of undefined
    at l.a.sequelize.authenticate.then (/usr/local/bin/aeirtu/node/webpack:/server.js:55:1)
    at tryCatcher (/usr/local/bin/aeirtu/node/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/usr/local/bin/aeirtu/node/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/usr/local/bin/aeirtu/node/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/usr/local/bin/aeirtu/node/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/usr/local/bin/aeirtu/node/node_modules/bluebird/js/release/promise.js:693:18)
    at Async._drainQueue (/usr/local/bin/aeirtu/node/node_modules/bluebird/js/release/async.js:133:16)
    at Async._drainQueues (/usr/local/bin/aeirtu/node/node_modules/bluebird/js/release/async.js:143:10)
    at Immediate.Async.drainQueues [as _onImmediate] (/usr/local/bin/aeirtu/node/node_modules/bluebird/js/release/async.js:17:14)
    at runCallback (timers.js:763:18)
    at tryOnImmediate (timers.js:734:5)
    at processImmediate (timers.js:716:5)

Here is my connection code:

My node.js code:

import express from "express";

import models from "./models";

const app = express();

models.sequelize
    .authenticate()
    .then(() => {
        console.log("Connected to repository");
    })
    .catch(err => {
        console.log("ERROR connecting to repository.");
        console.log(err);
    });

let port = 3001;
app.listen(port, () => {
    console.log("Server listening on port " + port);
});

My models.js:

import Sequelize from "sequelize";
import fs from "fs";
import path from "path";

const DATABASE_FILENAME = "test.db";

const fileWithPath = path.join(process.env.TEST_HOME, 'data', DATABASE_FILENAME);

let basename = path.basename(__filename);
let env = process.env.NODE_ENV || "development";
let db = {};

console.log("Connecting to repository at " + fileWithPath);

// database wide options
let opts = {
  dialect: "sqlite",
  storage: fileWithPath,
  define: {
    //prevent sequelize from pluralizing table names
    freezeTableName: true,
    // don't add the timestamp attributes (updatedAt, createdAt)
    timestamps: false
  },
  operatorsAliases: Sequelize.Op, // use Sequelize.Op https://github.com/sequelize/sequelize/issues/8417#issuecomment-334056048
};

let sequelize = new Sequelize(DATABASE_FILENAME, null, null, opts);

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (
      file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
    );
  })
  .forEach(file => {
    let 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;

export default db;

And a simple test code:

import db from "./models";

db.TestTable.findOne().then(data => {
    if (!data) console.log("ERROR FETCHING DATA");
    console.log(data.name);
});

I've triple checked: the sqlite3 file is in the correct location and the tables are there with data. For some reason I'm not being able to access then. I've also changed chmod a+rwx at the database file.

you forgot to import the *TestTable model`

db.TestTable = require('./TestTable')(sequelize, Sequelize);

your model.js should be a connection but there are no define model yet like

module.exports = (sequelize, DataTypes) => {  
    const testTable = sequelize.define('model', {
      states: {
        type:   Sequelize.ENUM,
        values: ['active', 'pending', 'deleted']
      }
    });

    return testTable;
};

Sample

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM