我正在尝试使用sequelize将记录插入MYSQL表。
安装了sequelize和mysql。
npm install --save sequelize
npm install --save mysql
在app.js
中定义它var Sequelize = require('sequelize');
db.js
var Sequelize = require('sequelize');
var sequelize = new Sequelize('randomdb', 'root', 'root', {
host: 'localhost',
dialect: 'mysql',
port : 8889,
pool: {
max: 5,
min: 0,
idle: 10000
}
});
exports.sequelize = sequelize;
module.exports = Sequelize;
路由/ index.js
var express = require('express');
var router = express.Router();
var sequelize = require('../db').sequelize;
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', {title: 'Express'});
});
router.get('/adduser', function (req, res) {
var User = sequelize.define('users', {
first_name: Sequelize.STRING
});
sequelize.sync().then(function () {
return User.create({
first_name: 'janedoe'
});
}).then(function (jane) {
console.log(jane.get({
plain: true
}))
});
});
module.exports = router;
这是错误。
无法读取未定义的属性'define'
TypeError:无法读取未定义
的属性'define'
缺少什么?
编辑2
db.js
var Sequelize = require('sequelize');
var sequelize = new Sequelize('randomdb', 'root', 'root', {
host: 'localhost',
dialect: 'mysql',
port: 8889,
pool: {
max: 5,
min: 0,
idle: 10000
},
define: {
timestamps: false
}
});
var db = {};
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
模型/ user.js的
var db = require('../db'),
sequelize = db.sequelize,
Sequelize = db.Sequelize;
var User = sequelize.define('random', {
first_name: Sequelize.STRING
});
module.exports = User;
路由/ index.js
var express = require('express');
var router = express.Router();
var db = require('../db'),
sequelize = db.sequelize,
Sequelize = db.Sequelize;
var User = require('../models/user');
router.get('/adduseryes', function (req, res) {
sequelize.sync().then(function () {
return User.create({
first_name: 'janedoe'
});
}).then(function (jane) {
res.send("YES");
});
});
module.exports = router;
答案 0 :(得分:9)
在db.js文件中,您将使用Sequelize var覆盖exports
变量。在node.js中,module.exports
== exports
。试试这个:
var Sequelize = require('sequelize');
var sequelize = new Sequelize(...);
var db = {};
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
然后,您可以修改routes / index.js中的导入,如下所示:
var db = require('../db'),
sequelize = db.sequelize,
Sequelize = db.Sequelize;