javascript - 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
随机。
解决方案
你需要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 });
推荐阅读
- android - Admob 广告没有展示,甚至没有测试广告
- c++ - 如何创建具有 CUDA 支持的最新 Tensorflow 版本的调试版本?
- java - 覆盖方法的值不反映主要变量
- php - 无法在php中访问会话变量
- vue.js - 使用 npm 包管理器安装时 b-tooltip css 不起作用
- java - 如何使用 `Collections.binarySearch()` 通过对象的 ArrayList 进行二进制搜索?
- python - 从矩阵python中的col/row迭代
- ios - 检查 Firebase 本地是否存在离线数据。(是否已上传)
- laravel - vuetify 仅触发最少 3 个字符的数据表搜索事件
- docker - Netflix/Conductor 打印了太多与 dynomite 相关的日志