Javascript TypeError:usert.addItem不是函数

Javascript TypeError:usert.addItem不是函数,javascript,node.js,sequelize.js,discord.js,Javascript,Node.js,Sequelize.js,Discord.js,正在尝试使用discord.js创建discord bot。我正在使用sequelize和sqlite创建一个数据库来存储数据。自定义函数似乎不起作用,终端在实际定义时认为它不是函数。这可能有一个非常明显的解决办法,但我非常业余,我经常出错,但通常会修复它们。这一次我甚至不能确定问题的根源 此问题也适用于其他自定义函数 最让人困惑的是,对于另一个bot的另一个文件夹来说,它完全可以工作,它的代码非常相似,基本上具有相同的自定义函数!但出于某种原因,它在这里不起作用 // Defining the

正在尝试使用discord.js创建discord bot。我正在使用sequelize和sqlite创建一个数据库来存储数据。自定义函数似乎不起作用,终端在实际定义时认为它不是函数。这可能有一个非常明显的解决办法,但我非常业余,我经常出错,但通常会修复它们。这一次我甚至不能确定问题的根源

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

最让人困惑的是,对于另一个bot的另一个文件夹来说,它完全可以工作,它的代码非常相似,基本上具有相同的自定义函数!但出于某种原因,它在这里不起作用

// 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 });
}; 
预期结果已成功添加到数据库,但终端返回:

节点:21400未处理PromisejectionWarning:TypeError:usert.addItem不是函数 添加await before Users.findByPk将以随机方式返回。

您需要等待Users.findByPkmessage.author.id

由于Users.findByPkmessage.author.id是一个承诺,它会将执行返回到下一个序列代码,因此变量const usert尚未初始化,这导致usert.addItem不是函数

您需要将const usert=Users.findByPkmessage.author.id更改为此。要完全初始化usert,addItem函数将可用:

const usert=await Users.findByPkmessage.author.id;
执行此操作将返回usert作为nullcheck message.author.id(如果它持有主键id)。如果它持有主键id,则检查您的数据库表以查看该id是否存在。我不明白?同一行在不同的文件夹上工作,但仍然返回null。执行此操作时返回null
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 });