gpt4 book ai didi

node.js - Sequelize - 无法读取未定义的属性 'define'

转载 作者:搜寻专家 更新时间:2023-10-31 22:38:24 24 4
gpt4 key购买 nike

我正在尝试使用 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;

这是错误。

Cannot read property 'define' of undefined

TypeError: Cannot read property 'define' of undefined

缺少什么?

编辑 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;

最佳答案

在您的 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;

关于node.js - Sequelize - 无法读取未定义的属性 'define',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33091197/

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