#javascript #node.js #sequelize.js
Вопрос:
У меня есть две модели, которые предназначены для пользователя и профиля
В моем Model/Index.js Файл Я использую приведенный ниже код для создания связи. Который создает столбец идентификатора пользователя в таблице моего профиля
db.User.hasOne(db.Profile, {
foriegnKey: {
type: DataTypes.UUID,
allowNull: false
}
})
db.Profile.belongsTo(db.User);
Я вставил данные в обе таблицы, но идентификатор пользователя всегда равен нулю.
Тогда моя проблема сейчас в том, как мне установить идентификатор пользователя в таблице профилей для работы с таблицей пользователей.
Пожалуйста, помогите мне,
я прочитал документ, но мне все еще не ясно.
Это мой файл маршрутов
const AuthController = require('./controllers/AuthController')
const AuthControllerPolicy = require ('./policies/AuthControllerPolicy')
const ProfileController = require('./controllers/ProfileController')
module.exports = (app) => {
app.post('/register',
AuthControllerPolicy.register,
AuthController.register)
app.post('/login',
AuthController.login)
app.get('/profile',
ProfileController.index)
app.post('/profile',
ProfileController.post)
}
Тогда у меня есть AuthContoller.js Файл
const {User} = require ('../models')
const jwt = require('jsonwebtoken')
const config = require('../config/config')
function jwtSignuser (user) {
const ONE_WEEK = 60 * 60 * 24 * 7
return jwt.sign(user, config.authentication.jwtSecret, {
expiresIn: ONE_WEEK
})
}
module.exports = {
async register (req, res) {
try {
const user = await User.create(req.body)
res.send(user.toJSON())
const userJson = user.toJSON()
res.send({
user: userJson,
token: jwtSignuser(userJson)
})
} catch (err) {
res.status(400).send({
error: 'This email account is already in use'
})
}
},
async login (req, res) {
try {
const {email, password} = req.body
const user = await User.findOne({
where: {
email: email
}
})
if (!user) {
res.status(403).send({
error: 'The Login Information was incorrect'
})
}
const isPasswordvalid = await user.comparePassword(password)
if(!isPasswordvalid){
res.status(403).send({
error: 'The Login Information was incorrect'
})
}
const userJson = user.toJSON()
res.send({
user: userJson,
token: jwtSignuser(userJson)
})
} catch (err) {
res.status(500).send({
error: 'Error occured trying to login'
})
}
}
}
Then Lastly this is my ProfileController.js File
const {Profile} = require ('../models')
const User = require('../models/Profile')
module.exports = {
async index (req, res) {
try {
const profile = await Profile.findOne({
where: {
id: User.id
}
})
res.send(profile)
}catch (err) {
res.status(500).send({
error: 'An Error has occured try again'
})
}
},
async post (req, res) {
try {
const profile = await Profile.create(req.body, User.id)
res.send(profile)
}catch (err) {
res.status(500).send({
error: 'An Error has occured try again'
})
}
}
}