TypeError: Cannot read property 'database' of undefined

狂风中的少年 提交于 2021-01-28 18:42:27

问题


I have two files-config.js and index.js The code I have written is as follows-

config.js-

module.exports={
    port:process.env.PORT || 8081,
    db:{
        database:process.env.DB_NAME|| 'tabtracker',
        user:process.env.DB_USER || 'tabtracker',
        password:process.env.DB_PASS|| 'tabtracker',
        options:{
            dialect:process.env.DIALECT ||'sqlite',
            host:process.env.HOST ||'localhost', 
            storage:'./tabtracker.sqlite'

        }
    }
}

index.js-

const fs=require('fs')
const path=require('path')
const Sequelize=require('sequelize')
const config=require('../config/config')
const db={}


const sequelize=new Sequelize(

    config.db.database,
    config.db.password,
    config.db.user,
    config.db.options
)


fs.readdirSync(__dirname)
 .filter((file)=>{
     file!=='index.js'
 }
 )
.forEach(file=>{
    const model=sequelize.import(path.join(__dirname,file));
    db[model.name]=model
})

db.sequelize=sequelize
db.Sequelize=Sequelize
module.exports=db

Why it is throwing error? I have imported the config.js properly in index.js. I have also declared config file properly.


回答1:


const config=('../config/config') - there is no require keyword here. So the config is not your config, just a string on the right. Hence accessing property of undefined, which is config.db.



来源:https://stackoverflow.com/questions/59227392/typeerror-cannot-read-property-database-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!