Nodejs Sequelize关系不起作用

时间:2017-12-12 15:32:39

标签: javascript mysql node.js sequelize.js

我试图创建用户可以对产品感兴趣的系统。有许多产品和几个用户可能对同一产品感兴趣。我已经按照教程(https://github.com/ianmunrobot/1702-express-review)进行了修改,并将其修改为我的目的,以创建seed.js脚本,该脚本为db创建以下表:兴趣,用户,使用database.js作为配置的产品。无论如何,当我试图在我的项目的其余部分使用相同的database.js文件时,我收到了错误。

user.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;

Products.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;

database.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)

1 个答案:

答案 0 :(得分:0)

由于声誉低于50,我无法添加评论。我猜测用户模型在您尝试使用时尚未就绪。你可以发布你的app.js或同等的?我怀疑“要求”之间可能存在不匹配的情况。某处和你的文件名。

我使用了您在上面提供的示例以及app.js中的以下行来要求database.js:

    var db = require('./database');

这对我来说很好。

但是,如果我将其更改为(大写&#39; D&#39;):

    var db = require('./Database');

我能够重现您遇到的错误。

您需要调用db.sync()将已定义的模型同步到数据库。

      db.sync({force: false})
        .then(message => {
            console.log('db synced');
        })
        .catch(function(err) {
            throw err;
        });

希望这有帮助。