我是节点新手。
我正在尝试使用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!');
})
}
config / 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´ on
var User = sequelize.define('user',{`
我做错了什么?
答案 0 :(得分:2)
在你的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;
}
答案 1 :(得分:1)
您应该要求将sequelize实例添加到用户模型中
配置/ db.js
module.exports = sequelize;
模型/ user.js的
var Sequelize = require('sequelize');
var sequelize = require('../config/db.js'); //sequelize instance
module.exports = function(application, req, res){
var User = sequelize.define('user', {
...
答案 2 :(得分:0)
对于使用Sequelize的项目,Sequelize-CLI是非常有用的工具。下载时
npm install -g sequelize-cli
然后您可以运行
sequelize init
上面的命令将为您写出一些文件夹,包括一个具有Ricardo上面创建的索引文件的models文件夹。这也提供了一些非常酷的环境配置。在new models文件夹中,您可以使用语法...使用对象创建新文件...
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;
}
虽然我确实喜欢将此作为工具。在此关键要注意,Sequelize会去寻找define()
方法的第一个参数。这样我们就可以写
module.exports = function(sequelize, DataType){
return sequelize.define("User", {
username: {
type: DataTypes.STRING
},
{
freezeTableName: true // Model tableName will be the same as the model name
}
});