我不确定实例是否被正确创建,但是我的模型似乎未定义。这是我的代码设置方式:
db.js
const fs = require("fs");
const path = require("path");
const Sequelize = require("sequelize");
const basename = path.basename(module.filename);
const env = process.env.NODE_ENV || "development";
const config = require(__dirname + "/config.js")[env];
const db = {};
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
var sequelize = new Sequelize(
config.database,
config.username,
config.password,
config
);
}
fs.readdirSync(path.join(__dirname, "models"))
.filter(function(file) {
return (
file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
);
})
.forEach(function(file) {
let model = sequelize["import"](path.join(__dirname, "models", file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
sequelize
.authenticate()
.then(() => {
console.log(`Connection was successful!`);
})
.catch(err => {
console.log(`Unable to connect to database: ${err}`);
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = {
db
};
Manifest.js(在models文件夹中)
"use strict";
module.exports = function(sequelize, DataTypes) {
let Manifest = sequelize.define("Manifest", {
manifestNumber: {
type: DataTypes.STRING(10),
primaryKey: true,
allowNull: false
},
huller: DataTypes.STRING(50),
address: DataTypes.STRING(50),
carrier: DataTypes.STRING(50),
driver: DataTypes.STRING(50),
dateShipped: DataTypes.DATE,
preparedBy: DataTypes.STRING(15),
recievedBy: DataTypes.STRING(15),
truckLicenseNumber: DataTypes.STRING(25),
frontTrailerLicenseNumber: DataTypes.STRING(25),
rearTrailerLicenseNUmber: DataTypes.STRING(25),
splitLoad: DataTypes.BOOLEAN,
tagNumber: DataTypes.STRING(50),
grossTotal: DataTypes.DECIMAL(18, 0),
netTotal: DataTypes.DECIMAL(18, 0),
totalBins: DataTypes.DECIMAL(18, 0),
phase: DataTypes.STRING(10),
shipments: DataTypes.INTEGER,
submitDate: {
type: DataTypes.DATEONLY,
defaultValue: DataTypes.NOW,
allowNull: false
}
});
return Manifest;
};
api.js(摘要)
const db = require("../db");
const express = require("express");
const router = express.Router();
router.post("/manifests/new", function(req, res) {
let manifest = req.body;
db.Manifest.max("manifestNumber")
.success(max => {
if (max) {
// Convert max to int, add 1, then post with new manifest
} else {
// Empty table so start with 1
}
})
.error(err => {
console.log(`Error querying max: ${err}`);
});
})
我确保文件名与模型中定义的完全匹配,但是当我的db.js读取models目录并将其添加到db变量时,我不确定这是否重要。是将代码包含在api.js中时,是代码的结构方式还是滥用db?我知道这段代码可以正确连接到我的SQL Server实例,但是这可能是该模型没有正确链接到现有表吗?还是表此时恰好是空的?此Sequelize新手将不胜感激!
答案 0 :(得分:0)
在Sequelize中,您不需要将所有模型放入变量中...
当您自动使用sequelize.import
时,您将拥有sequelize.models
(从模型文件夹中导入的所有模型的数组)和sequelize.model
函数,并且您必须使用以下内容:sequelize.model('Manifest')
db.js
const Sequelize = require('sequelize')
const fs = require('fs')
const path = require('path')
module.exports = ({ logger, config }) => {
config.db.logging = (
config.db.logging !== false
? query => logger.debug('[DATABASE]', query)
: false
)
const db = new Sequelize(config.db)
loadModels(db)
Object
.keys(db.models)
.forEach((model) => {
if ('associate' in db.model(model)) {
db.model(model).associate()
}
})
return db
}
// ===============================================
function loadModels (sequelize) {
const dir = path.join(__dirname, 'models')
fs.readdirSync(dir)
.forEach(
file => sequelize.import(path.join(dir, file))
)
}
我在loadModels
函数中没有任何一致性,因为model文件夹中的所有文件都必须导出序列化模型。
关于您的错误。检查您的Object.keys(db)
是否确实有您的模型,因为您的readdirSync
似乎是错误的。所以检查一下。