addProject 不是一个函数(Sequelize)



在我的应用程序中,我已经在User表和Project表之间建立了关联。 使用此代码:

User.belongsToMany(Project, {
through: "users_projects"
});
Project.belongsToMany(User, {
through: "users_projects"
});

当我执行简单的发布请求时,出现以下错误:

currentUser.addProject 不是一个函数

app.post("/project", async (req, res, next) => {
try {
const project = await Project.findOrCreate({
where: {
name: req.body.name,
content: req.body.content
}
});
const currentUser = await User.findAll({
where: { id: req.body.userId }
});
console.log(currentUser);
await currentUser.addProject(project[0]);
res.json(project[0]);
} catch (error) {
next(error);
}
});

什么可能导致此问题?

findAll返回一个数组,所以你的代码应该是

await currentUser[0].addProject(project[0])

但是,如果使用id进行查询,则可以使用findByPk来获取对象。

const currentUser = await User.findByPk(req.body.userId);
await currentUser.addProject(project[0])

最新更新