javascript - How export and use models in sequelize - Stack Overflow

i use sequelize in my node.js project, and i dont know how to export and use table model in another fil

i use sequelize in my node.js project, and i dont know how to export and use table model in another file. I save table models in folder for example Profile.js

module.exports = (sequielize, DataTypes) => sequielize.define('Profile', {
  ID: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true,
    allowNull: false
  },
  Login: {
    type: DataTypes.STRING(24),
    allowNull: false
  },
  SocialClub: {
    type: DataTypes.STRING(128),
    allowNull: false
  },
  Email: {
    type: DataTypes.STRING(64),
    allowNull: false
  },
  RegIP: {
    type: DataTypes.STRING(17),
    allowNull: false
  },
  LastIP:
  {
    type: DataTypes.STRING(17),
    allowNull: false
  },
  RegDate: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW,
    allowNull: false
  },
  LastDate: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW,
    allowNull: false
  }
});

And I have such database module database.js:

const Sequelize = require('sequelize');
const fs = require('fs')
const path = require('path')
const config = require('../configs/server_conf');

db = {};

const sequelize = new Sequelize(
    config.db_settings.database,
    config.db_settings.user,
    config.db_settings.password,
    config.db_settings.options);

db.sequelize = sequelize;
db.Sequelize = Sequelize;

db.checkConnection = async function() {
    sequelize.authenticate().then(() => {

        console.log('Подключение к базе данных прошло успешно!');

        //import db models
        fs.readdirSync(path.join(__dirname, '..', 'models')).forEach(file => {
            var model = sequelize.import(path.join(__dirname, '..', 'models', file));
            db[model.name] = model;

        });

        sequelize.sync({
            force: true
        }).then(() => {
            console.log('synchroniseModels: Все таблицы были созданы!');
        }).catch(err => console.log(err));

        mp.events.call("initServerFiles");

    }).catch(err => {
        console.error('Невозможно подключиться к базе данных:', err);
    });
}

module.exports = db;

And i have such an index.js file where i'm exporting checkConnection function:

"use strict"

const fs = require('fs');
const path = require('path');

const { checkConnection } = require('./modules/database.js');
var Events = [];

mp.events.add(
{
    "initServerFiles" : () =>
    {
        fs.readdirSync(path.resolve(__dirname, 'events')).forEach(function(i) {
            Events = Events.concat(require('./events/' + i));
        });

        Events.forEach(function(i) {
            mp.events.add(i);
            console.log(i);
        });

        mp.events.call('initServer');

        console.log("Загрузка всех файлов прошла успешно!");
    }
});

checkConnection();

So in a nutshell, how i can export my Profile table and use it, for example:

Profile.create({
            Login: "0xWraith",
            SocialClub: "0xWraith",
            Email: "[email protected]",
            RegIP: "127.0.0.1",
            LastIP: "127.0.0.1",
            LastDate: "07.04.2020"
        }).then(res => {
             console.log(res);
        }).catch(err=>console.log(err));

i use sequelize in my node.js project, and i dont know how to export and use table model in another file. I save table models in folder for example Profile.js

module.exports = (sequielize, DataTypes) => sequielize.define('Profile', {
  ID: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true,
    allowNull: false
  },
  Login: {
    type: DataTypes.STRING(24),
    allowNull: false
  },
  SocialClub: {
    type: DataTypes.STRING(128),
    allowNull: false
  },
  Email: {
    type: DataTypes.STRING(64),
    allowNull: false
  },
  RegIP: {
    type: DataTypes.STRING(17),
    allowNull: false
  },
  LastIP:
  {
    type: DataTypes.STRING(17),
    allowNull: false
  },
  RegDate: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW,
    allowNull: false
  },
  LastDate: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW,
    allowNull: false
  }
});

And I have such database module database.js:

const Sequelize = require('sequelize');
const fs = require('fs')
const path = require('path')
const config = require('../configs/server_conf');

db = {};

const sequelize = new Sequelize(
    config.db_settings.database,
    config.db_settings.user,
    config.db_settings.password,
    config.db_settings.options);

db.sequelize = sequelize;
db.Sequelize = Sequelize;

db.checkConnection = async function() {
    sequelize.authenticate().then(() => {

        console.log('Подключение к базе данных прошло успешно!');

        //import db models
        fs.readdirSync(path.join(__dirname, '..', 'models')).forEach(file => {
            var model = sequelize.import(path.join(__dirname, '..', 'models', file));
            db[model.name] = model;

        });

        sequelize.sync({
            force: true
        }).then(() => {
            console.log('synchroniseModels: Все таблицы были созданы!');
        }).catch(err => console.log(err));

        mp.events.call("initServerFiles");

    }).catch(err => {
        console.error('Невозможно подключиться к базе данных:', err);
    });
}

module.exports = db;

And i have such an index.js file where i'm exporting checkConnection function:

"use strict"

const fs = require('fs');
const path = require('path');

const { checkConnection } = require('./modules/database.js');
var Events = [];

mp.events.add(
{
    "initServerFiles" : () =>
    {
        fs.readdirSync(path.resolve(__dirname, 'events')).forEach(function(i) {
            Events = Events.concat(require('./events/' + i));
        });

        Events.forEach(function(i) {
            mp.events.add(i);
            console.log(i);
        });

        mp.events.call('initServer');

        console.log("Загрузка всех файлов прошла успешно!");
    }
});

checkConnection();

So in a nutshell, how i can export my Profile table and use it, for example:

Profile.create({
            Login: "0xWraith",
            SocialClub: "0xWraith",
            Email: "[email protected]",
            RegIP: "127.0.0.1",
            LastIP: "127.0.0.1",
            LastDate: "07.04.2020"
        }).then(res => {
             console.log(res);
        }).catch(err=>console.log(err));
Share Improve this question edited Apr 8, 2020 at 14:13 0xWraith asked Apr 8, 2020 at 14:08 0xWraith0xWraith 991 gold badge1 silver badge9 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

So you already have all registered models in the database.js module. Just import the whole database.js like this:

const db = require('./modules/database.js');
...
db.Profile.create({
            Login: "0xWraith",
            SocialClub: "0xWraith",
            Email: "[email protected]",
            RegIP: "127.0.0.1",
            LastIP: "127.0.0.1",
            LastDate: "07.04.2020"
        }).then(res => {
             console.log(res);
        }).catch(err=>console.log(err));

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744309335a4567873.html

相关推荐

  • javascript - How export and use models in sequelize - Stack Overflow

    i use sequelize in my node.js project, and i dont know how to export and use table model in another fil

    7天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信