sqllite3 Node.js数据库控制器(this.dao.run不是函数)

时间:2019-06-23 13:37:21

标签: javascript node.js

我正在尝试设计数据库sqllite3控制器,但出现错误:

TypeError:this.dao.run不是函数

at ProjectRepository.createTable (/home/alexa/abc/project_repository:13:21)
at main (/home/alexa/abc/main.js:14:15)

为什么?我真的很想写一个更高的杠杆应用程序

我的结构: dao.js

const sqlite3 = require('sqlite3')
class AppDAO {
  constructor(dbFilePath) {
    this.dao = new sqlite3.Database(dbFilePath, (err) => {
      if (err) {
        console.log('Could not connect to database', err)
      } else {
        console.log('Connected to database')
      }
    })
  }
}

module.exports = AppDAO

ProjectRepository:

class ProjectRepository {
  constructor(dao) {
    this.dao = dao;
  }

  createTable() {
    const sql = `
    CREATE TABLE IF NOT EXISTS projects (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT)`;
    return this.dao.run(sql);
  }

  create(name) {
    return this.dao.run(
        'INSERT INTO projects (name) VALUES (?)',
        [name]);
  }
}

module.exports = ProjectRepository;

主类:

const AppDAO = require('./dao');
const ProjectRepository = require('./project_repository');


// eslint-disable-next-line require-jsdoc
function main() {
  const dao = new AppDAO('./database.sqlite3');
  const blogProjectData = {name: 'Write Node.js - SQLite Tutorial'};
  const projectRepo = new ProjectRepository(dao);


  projectRepo.createTable()
      .then(() => projectRepo.createTable())
      .then(() => projectRepo.create(blogProjectData.name));
}

main();

1 个答案:

答案 0 :(得分:1)

您传递给dao的{​​{1}}变量包含类型为new ProjectRepository(dao)的对象,而您的AppDAO类没有函数AppDAO

因此,请在您的run对象的run属性上调用dao

AppDAO

或为 createTable() { const sql = ` CREATE TABLE IF NOT EXISTS projects ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)`; return this.dao.dao.run(sql); } 添加一个run函数,该函数使用Function.prototype.apply()将呼叫转发到AppDAO属性

dao