node.js - Json无法读取未定义的属性

标签 node.js discord.js

当我在不和谐机器人中执行命令时(当我输入正常消息时不会发生错误)时,我收到一条错误消息:

Cannot read property 'active' of undefined

当我尝试从存储用户数据的 json 文件中控制台记录对象时,就会发生这种情况。

这些是我的机器人的index.js 文件的第一行代码,我尝试控制台日志的行是发生错误的地方

const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require("fs");
const prefix = '>';

let xp = require("./storage/dbGeneral.json");
let pr = require("./storage/dbPremium.json");
let lv = require("./storage/levels.json");

client.on('message', message => {
    console.log(pr[message.author.id].active);
}

这是我存储数据的json文件

{
  "397387465024864257": {
    "active": false,
    "dateStart": "",
    "dateEnd": ""
  }
}

这是错误:

index.js:14
    console.log(pr[message.author.id].active);
                                      ^

TypeError: Cannot read property 'active' of undefined
    at Client.client.on.message (index.js:14:39)
    at emitOne (events.js:116:13)
    at Client.emit (events.js:211:7)
    at MessageCreateHandler.handle (\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
    at WebSocketPacketManager.handle (\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:103:65)
    at WebSocketConnection.onPacket (\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
    at WebSocketConnection.onMessage (\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
    at WebSocket.onMessage (\node_modules\ws\lib\event-target.js:120:16)
    at emitOne (events.js:116:13)
    at WebSocket.emit (events.js:211:7)

我真的不知道错误的原因是什么,所有其他 json 请求都可以使用相同的方法正常工作。

最佳答案

该错误是由于尝试访问未定义的属性而引起的。 要解决您的问题,您必须检查数据库中是否存在该用户。

let user = pr[message.author.id];
if(user) console.log(user.active)

关于node.js - Json无法读取未定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56850844/

相关文章:

javascript - Express JS 中的正文解析器

javascript - 具有Play框架的React.js-服务器端渲染

node.js - 如何将来自容器的所有流量路由到同一个 Kubernetes pod 中的另一个容器?

javascript - 如何创建 channel 然后找到ID

javascript - 显示冷却剩余时间

javascript - Discord.js:随机化存储为 json 文件的数组内容

node.js - S3 存储桶 Lambda 事件 : Unable to validate the following destination configurations

javascript - 弃用警告 : Collection#find: pass a function instead

javascript - 从 DM 向用户添加角色?

javascript - 在多个浏览器中登录时如何更新更改的用户数据