2017-12-12 8 views
0

사용자가 제품에 관심을 가질 수있는 시스템을 만들려고합니다. 많은 제품이 있고 몇몇 사용자는 동일한 제품에 관하여 흥미있을 수 있습니다. 나는 튜토리얼 (https://github.com/ianmunrobot/1702-express-review)을 따르고 데이터베이스에 다음 테이블을 생성하는 seed.js 스크립트를 작성하기 위해 그것을 수정했다. Interests, Users, database.js를 구성으로 사용하는 제품. 어쨌든 내 프로젝트의 나머지와 동일한 database.js 파일을 사용하려고 할 때 오류가 발생했습니다.Nodejs Sequelize relationship not working

의 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) 
+0

User.js의 내용을 게시 할 수 있습니까? – asosnovsky

+0

User.js와 Product.js를 추가했습니다. – kaaleppi3

+0

'through'는 문자열이 아닌 sequelize 모델이어야합니다. 오류가 무엇입니까? – yBrodsky

답변

0

내가 인해 사용자 모델은 당신이 그것을 사용하려고하는 시점에서 준비되지 않은 것이 될 것이다 덜 (50) 내 생각보다 명성을 가지고에 주석을 추가 할 수 없습니다입니다. app.js 또는 이와 동등한 항목을 게시 할 수 있습니까? 나는 어딘가에 당신의 파일 이름과 '요구'사이의 불일치가있을 수 있다고 생각합니다.

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

이 나를 위해 잘 작동 :

나는 database.js을 필요로하는 당신이 위에 제공 한 예와 app.js에 다음 줄을 사용했다. I가 (대문자 'D')를 변경하는 경우

그러나 :

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

을 나는 당신이 발생하는 오류를 재현 할 수 있어요.

정의 된 모델을 DB에 동기화하려면 db.sync()를 호출해야합니다.

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

희망 사항.

+0

app.js 추가 모델 파일에 데이터베이스를 요구하는 것만으로 충분하지 않습니까? – kaaleppi3

+0

정의 된 모델을 DB에 동기화하려면 db.sync()를 호출해야합니다. – Faz