首页 > 解决方案 > TypeError:usert.addItem 不是函数

问题描述

尝试使用 discord.js 制作一个不和谐的机器人。我正在使用 sequelize 和 sqlite 创建一个数据库来存储数据。自定义函数似乎不起作用,终端在实际定义时认为它不是函数。对此可能有一个非常明显的解决方案,但我非常业余,我经常遇到错误,但通常会修复它们。这个我什至无法确定问题的根源

这个问题也适用于其他自定义函数

最令人困惑的是,对于另一个完全用于另一个机器人的文件夹,具有非常相似的代码和基本相同的自定义功能,它可以工作!但由于某种原因,它在这里不起作用。

// Defining these 
const { Users, ItemDB } = require('./dbObjects');



// The command that uses the function. It is worth noting that it finds the item and user successfully, proving that the problem is in users.addItem
const item = await ItemDB.findByPk(1);
const usert = Users.findByPk(message.author.id);
usert.addItem(item);

// The addItem function defined, in dbObjects file
Users.prototype.addItem = async function(item) {
const useritem = await UserItems.findOne({
    where: { user_id: this.user_id, item_id: item.id },
});

if (useritem) {
    useritem.amount += 1;
    return useritem.save();
}

return UserItems.create({ user_id: this.user_id, item_id: item.id, amount: 1 });
}; 

预期结果已成功添加到数据库,但终端返回:

(node:21400) UnhandledPromiseRejectionWarning: TypeError: usert.addItem is not a function

await在返回之前添加Users.findByPk随机。

标签: javascriptnode.jssequelize.jsdiscord.js

解决方案


你需要await Users.findByPk(message.author.id);

const { Users, ItemDB } = require('./dbObjects');



// The command that uses the function. It is worth noting that it finds the item and user successfully, proving that the problem is in users.addItem
const item = await ItemDB.findByPk(1);
const usert = await Users.findByPk(message.author.id);
usert.addItem(item);

// The addItem function defined, in dbObjects file
Users.prototype.addItem = async function(item) {
const useritem = await UserItems.findOne({
    where: { user_id: this.user_id, item_id: item.id },
});

if (useritem) {
    useritem.amount += 1;
    return useritem.save();
}

return UserItems.create({ user_id: this.user_id, item_id: item.id, amount: 1 });



推荐阅读