gpt4 book ai didi

javascript - sequelize 未定义 - Sequelize 和 consign

转载 作者:行者123 更新时间:2023-11-30 11:46:39 25 4
gpt4 key购买 nike

我是 node 新手。

我正在尝试使用 cosign 在我的简单应用程序中添加 Sequelize。

配置/db.js

var Sequelize = require('sequelize');

var sequelize = new Sequelize('test', 'root', '', {

host: 'localhost',
dialect: 'mysql',

pool: {
max: 5,
min: 0,
idle: 10000
}

});

module.exports = function () {
return sequelize
}

模型/user.js

var Sequelize = require('sequelize');

module.exports = function(application, req, res){

var User = sequelize.define('user', {
username: {
type: Sequelize.STRING,
}
}, {
freezeTableName: true // Model tableName will be the same as the model name
});

User.create({ username: 'fnord'})
.then(function() {
console.log('criado!');
})
}

配置/server.js

...
consign()
.include('app/routes')
.then('config/db.js')
.then('app/models')
.then('app/controllers')
.into(app);

module.exports = app;

我收到错误 sequelize is not defined´ onvar User = sequelize.define('user', {`

我做错了什么?

最佳答案

像这样在您的 moldes 文件夹中创建一个 index.js 文件:

"use strict";

var fs = require("fs");
var path = require("path");
var Sequelize = require("sequelize");

var sequelize = new Sequelize(global.config.dbConfig.name, global.config.dbConfig.user, global.config.dbConfig.password, {
host: global.config.dbConfig.host,
port: global.config.dbConfig.port,
pool: false
});

var db = {};

fs.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf(".") !== 0) && (file !== "index.js");
})
.forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});

Object.keys(db).forEach(function(modelName) {
if ("associate" in db[modelName]) {
db[modelName].associate(db);
}
});

db.sequelize = sequelize;

module.exports = db;

然后在你的 user.js 中做这样的事情:

module.exports = function(sequelize, DataTypes) {
var User = sequelize.define("User", {
username: {
type: DataTypes.STRING
},
{
freezeTableName: true // Model tableName will be the same as the model name
}
});

return User;
}

http://docs.sequelizejs.com/en/1.7.0/articles/express/

关于javascript - sequelize 未定义 - Sequelize 和 consign,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40764916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com