我正在尝试创建用户可以对产品感兴趣的系统。产品有很多,并且多个用户可能对同一产品感兴趣。我遵循了教程( https://github.com/ianmunrobot/1702-express-review )并根据我的目的修改了它以创建seed.js脚本,该脚本使用database.js作为配置创建以下表到数据库:兴趣、用户、产品。无论如何,当我尝试在项目的其余部分使用相同的database.js 文件时,我收到错误。
用户.js
// The User model.
const Sequelize = require('sequelize');
const bcrypt = require('bcrypt');
const config = require('../config');
const db = require('../database');
const Product = require('./Product');
// 1: The model schema.
const modelDefinition = {
username: {
type: Sequelize.STRING,
unique: true,
allowNull: false
},
email: {
type: Sequelize.STRING,
unique: true,
allowNull: false
},
password: {
type: Sequelize.STRING,
allowNull: false,
},
role: {
type: Sequelize.STRING,
allowNull: true,
},
};
// 2: The model options.
const modelOptions = {
instanceMethods: {
comparePasswords: comparePasswords,
},
hooks: {
beforeValidate: hashPassword
},
};
// 3: Define the User model.
const UserModel = db.define('User', modelDefinition, modelOptions);
// Compares two passwords.
function comparePasswords(password, callback) {
bcrypt.compare(password, this.password, function (error, isMatch) {
if (error) {
return callback(error);
}
return callback(null, isMatch);
});
}
// Hashes the password for a user object.
function hashPassword(user) {
if (user.changed('password')) {
return bcrypt.hash(user.password, 10).then(function (password) {
user.password = password;
});
}
}
module.exports = UserModel;
产品.js
const Sequelize = require('sequelize');
const db = require('../database');
const User = require('./User');
const ProductModel = db.define('Product', {
name: {
type: Sequelize.STRING,
allowNull: false,
},
price: {
type: Sequelize.INTEGER,
},
});
module.exports = ProductModel;
数据库.js:
const Sequelize = require('sequelize');
const config = require('./config');
const db = new Sequelize(
config.db.name,
config.db.user,
config.db.password,
config.db.details,
);
module.exports = db;
const User = require('./models/User.js');
const Product = require('./models/Product.js');
Product.belongsToMany(User, { as: 'users', through: 'Interests' });
app.js:
const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const promisify = require('es6-promisify');
const morgan = require('morgan');
const sequelize = require('sequelize');
const passport = require('passport');
const jwt = require('jsonwebtoken');
const hookJWTStrategy = require('./passportStrategy');
const routes = require('./routes/index');
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Headers', 'Origin, Content-Type, Authorization, x-id, Content-Length, X-Requested-with');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
next();
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(passport.initialize());
// Hook the passport JWT strategy.
hookJWTStrategy(passport);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use((err, req, res, next) => {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
预期结果是用户可能对产品感兴趣。兴趣应该在兴趣表中,并且用户应该能够对许多产品感兴趣。
错误:
Error: Product.belongsToMany called with something that's not an instance of Sequelize.Model
at Model.Mixin.belongsToMany (/home/mikko/git/s/node_modules/sequelize/lib/associations/mixin.js:252:11)
at Object.<anonymous> (/home/mikko/git/s/database.js:17:9)
最佳答案
由于声誉低于 50,我无法添加评论。我的猜测是用户模型在您尝试使用它时尚未准备好。您可以发布您的 app.js 或同等内容吗?我怀疑某处的“require”与您的文件名之间可能不匹配。
我使用了您上面提供的示例以及 app.js 中的以下行来要求 database.js:
var db = require('./database');
这对我来说效果很好。
但是,如果我将其更改为(大写“D”):
var db = require('./Database');
我能够重现您遇到的错误。
您需要调用 db.sync() 将定义的模型同步到数据库。
db.sync({force: false})
.then(message => {
console.log('db synced');
})
.catch(function(err) {
throw err;
});
希望这有帮助。
关于javascript - Nodejs Sequelize 关系不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47776198/