gpt4 book ai didi

node.js - NodeJS Sequelize : Association with alias [alias] does not exist on [model]

转载 作者:行者123 更新时间:2023-11-29 13:39:06 47 4
gpt4 key购买 nike

我正在为一个学校项目使用 NodeJS 和 Sequelize,我正在努力与 sequelize 工作建立联系。我之前尝试过一些东西,但没有一个让我开心。

基本上,一个用户可以拥有多个播放列表 (hasMany)。一个播放列表属于一个用户(belongsTo)。

我的错误是:用户不存在与别名“播放列表”的关联

这是我的模型:

/* USER MODEL */
const Sequelize = require('sequelize');
const { db } = require('../utils/db');

const User = db.define('users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
userID: {
type: Sequelize.INTEGER,
allowNull: false,
field: 'user_id',
},
firstName: {
type: Sequelize.STRING,
field: 'first_name',
allowNull: false,
},
}, {
underscored: true,
tableName: 'users',
freezeTableName: true, // Model tableName will be the same as the model name
});

module.exports = {
User,
};
/* PLAYLIST MODEL */

const sequelize = require('sequelize');
const { db } = require('../utils/db');

const Playlist = db.define('playlist', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: sequelize.INTEGER,
},
name: {
type: sequelize.STRING,
field: 'name',
allowNull: false,
},
coverUrl: {
type: sequelize.STRING,
field: 'cover_url',
allowNull: true,
},
ownerId: {
type: sequelize.INTEGER,
allowNull: false,
references: {
model: 'users',
key: 'user_id',
},
},
}, {
underscored: true,
tableName: 'playlist',
freezeTableName: true,
});

module.exports = {
Playlist,
};

这是我加载模型的方式:

const { Credentials } = require('./credentials');
const { User } = require('./users');
const { Playlist } = require('./playlist');

function loadModels() {
User.associate = (models) => {
User.hasMany(models.Playlist, { as: 'playlist' });
};

Playlist.associate = (models) => {
Playlist.belongsTo(models.User, { foreignKey: 'owner_id', as: 'owner' });
};

Credentials.sync({ force: false });
User.sync({ force: false });
Playlist.sync({ force: false });
}

module.exports = {
loadModels,
};

最后这是我收到此错误的查询:

const express = require('express');
const { auth } = require('../../middlewares/auth');
const { Playlist } = require('../../models/playlist');
const { User } = require('../../models/users');

const router = express.Router();

router.get('/playlist', [], auth, (req, res) => {
User.findOne({
where: { userID: req.user.user_id }, include: 'playlist',
}).then((r) => {
console.log(r);
});
});

module.exports = router;

我正在尝试获取属于某个用户的所有播放列表。

我删除了所有无用的代码(jwt 检查等)因此,当我在/playlist 上执行获取请求时,我得到:未处理的拒绝错误:用户不存在与别名“播放列表”的关联

我理解这个错误,但不明白为什么会出现这个错误。我错过了什么,有什么想法吗?

谢谢,

最佳答案

我最终通过迁移重新制作所有模型和定义来修复它。我遇到了同样的问题,解决方案是 Sequelize 将模型名称复数化,所以在我的情况下,用户不存在“播放列表”,因为 Sequelize 将我的模型复数化,所以我不得不改用“播放列表”。

关于node.js - NodeJS Sequelize : Association with alias [alias] does not exist on [model],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58086800/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com