有错误:
findById
不是函数
当我尝试执行Node js应用程序时。
这是我的代码,专门用于电子商务网站。
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const errorController = require('./controllers/error');
const sequelize = require('./util/database');
const Product = require('./models/product');
const User = require('./models/user');
const app = express();
app.set('view engine', 'ejs');
app.set('views', 'views');
const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
// findById方法
app.use((req, res, next) => {
User.findById(1)
.then(user => {
req.user = user;
next();
})
.catch(err => console.log(err));
});
//路由控制器
app.use('/admin', adminRoutes);
app.use(shopRoutes);
app.use(errorController.get404);
Product.belongsTo(User, { constraints: true, onDelete: 'CASCADE' });
User.hasMany(Product);
// sequelize语句
sequelize
// .sync({ force: true })
.sync()
.then(result => {
return User.findById(1);
// console.log(result);
})
.then(user => {
if (!user) {
return User.create({ name: 'Max', email: 'test@test.com' });
}
return User;
})
.then(user => {
// console.log(user);
//端口配置
app.listen(3000,() => console.log(`looking at local host port number 3000`));
})
.catch(err => {
console.log(err);
});
答案 0 :(得分:0)
此错误意味着在用户模型中未定义findById。您需要在“ ./models/user”模块中添加和导出此方法。
答案 1 :(得分:0)
我认为您希望Model方法findByPk“通过其主键搜索单个实例。”)尝试:
app.use((req, res, next) => {
User.findByPk(1)
.then(user => {