我在我的node.js项目中使用sequelize,我不知道如何导出和使用另一个文件中的表格模型。我将表格模型保存在文件夹中,例如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
}
});
并且我有这样的数据库模块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;
我有这样一个index.js文件,我在其中导出checkConnection函数:
"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();
因此,简单地说,我可以如何导出我的配置文件表并使用它,例如:
Profile.create({
Login: "0xWraith",
SocialClub: "0xWraith",
Email: "mail@gmail.com",
RegIP: "127.0.0.1",
LastIP: "127.0.0.1",
LastDate: "07.04.2020"
}).then(res => {
console.log(res);
}).catch(err=>console.log(err));
1条答案
按热度按时间rsaldnfx1#
因此,您已经在database.js模块中拥有了所有注册的模型,只需导入整个database.js,如下所示: