javascript - TypeError : usert. addItem 不是函数

标签 javascript node.js sequelize.js discord.js

尝试使用 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

最佳答案

你需要 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 });


关于javascript - TypeError : usert. addItem 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54337358/

相关文章:

javascript - 当我们使用 join 方法时,根据根表的 id 进行排序

javascript - 在 Javascript 中,你能扩展 DOM 吗?

javascript - 无法使用 Sigma.js 显示任何图表

node.js - SequelizeJS - 使用原始查询将 JSONB 插入到 Postgres - 如何转义

javascript - 在单个快速处理程序中处理 multipart/formdata、application/json 和 text/plain?

javascript - Node.js Docker 镜像环境变量

node.js - Sequelize - 根据标题中的术语过滤帖子?

javascript - 获取 twitter 和 google plus 共享计数或任何替代

javascript - 水平布置许多 div,但要让较低的行在第一行下方紧密填充

javascript - 仅在nodejs上使用mongoose列出所有GridFs元数据