sequelize.import is not a function

后端 未结 3 812
梦毁少年i
梦毁少年i 2021-02-13 04:33

I\'m new to express.

I want to import files to sequelize and declared:

const model = sequelize.import(path.join(__dirname, file))

                                 


        
相关标签:
3条回答
  • 2021-02-13 04:41

    The error is caused by using the sequelize import object. Instead you should use Node's built in CommonJS require function. So change this line in your models/index.js:

    const model = sequelize['import'](path.join(__dirname, file))
    

    to:

    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes)
    

    You can also just regenerate the models directory and readd your models without the old index.js if you find that easier:

    mv models models.bak && sequelize init:models && mv models.bak/index.js models.bak/index.js.bak && mv models.bak/* models/ && rm models.bak
    

    That one liner will fix your problem if you have sequelize-cli installed globally. If you don't you can use this one:

    npm i --save-dev sequelize-cli && mv models models.bak && npx sequelize init:models && mv models.bak/index.js models.bak/index.js.bak && mv models.bak/* models/ && rm models.bak
    

    You may also need to update your config folder. I use a JavaScript config to inject ENVs, so I had to add to change my const config = require(... line to reflect that. If you used one of my one liners your old models/index.js file is now at index.js.bak if you need to grab any custom stuff from it.

    0 讨论(0)
  • 2021-02-13 04:54

    Check if you have exported the model using old JavaScript syntax.

    In my case, it was enough to change the code from:

    export default (sequelize, DataTypes) => {
        ...
    }
    

    to

    module.exports = (sequelize, DataTypes) => {
        ...
    }
    
    0 讨论(0)
  • 2021-02-13 05:05

    As of now I was able to fix the issue by downgrading the sequelize module version in your package.json to "sequelize": "^5.22.3",. do let me know if it is also fixed on your side.

    Edit: any sequelize version under < 6.0.0 should work as normal

    0 讨论(0)
提交回复
热议问题