The "discord.js" module is throwing an error stating that the property for

Currently, I am in the process of developing a Discord bot using discord.js. As part of this project, I am incorporating JSON functionality to store information for individual users in a separate file. However, I have encountered an issue where an error message stating that planet is not defined pops up at the line containing

if (bot.log[mentionedGuyName].planet == undefined) {
. Due to the extensive length of my code, I cannot include it all here.

The main objective of this particular code segment is to check if a user already has a "planet" assigned. If they do, the bot retrieves the value from the JSON file and sends it to the channel. If not, it selects a random one (additional code omitted).

I believe I have a basic understanding of why this error is occurring (undefined planet property), but I am uncertain about how to resolve it. Any assistance on how to define a JSON property or address this issue would be greatly appreciated by myself and my server members. Thank you in advance!

Below is a snippet of my JavaScript file:

let mentionedGuy = message.mentions.members.first();
let mentionedGuyName = null;
let noMentions = message.mentions.members.first() == false || 
message.mentions.members.first() == undefined;
if (noMentions) return;
else mentionedGuyName = mentionedGuy.user.username;

if (message.content.startsWith(prefix + "planet")) {
    if (message.content.length > 7) {
        if (bot.log[mentionedGuyName].planet == undefined) {
            bot.log[mentionedGuyName] = {
                planet: jMoon
                }
                fs.writeFile('./log.json', JSON.stringify(bot.log, null, 4), err => {
                    if (err) throw err;
                });
                message.channel.send(targeting);
                message.channel.send(coords);
        } else {
            message.channel.send(bot.log[mentionedGuyName].planet);
        }
    }
}

Answer №1

Modify the code to verify the data type

if(typeof <var> === 'undefined') //evaluates to true if variable is undefined

Keep in mind that typeof operator always returns a string value Source

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble displaying a set of data points in a React component

Exploring React, I have built a test app and performed an API call to fetch a large JSON object. After breaking it down into 10 arrays with 3 props each, I am now facing a challenge in sending this data to another component. Despite being able to log the ...

Identifying a specific string value in an array using jQuery or JavaScript

Currently, I am working on checking for duplicate values in an array that I have created. My approach involves using a second array called tempArray to compare each value from the original array (uniqueLabel) and determine if it already exists. If the val ...

Editing a video directly within the browser prior to uploading it

For my new video upload platform, I am looking to give users the ability to trim their videos directly in their browser before uploading to the cloud storage. Can anyone suggest a Javascript solution for this feature? ...

Switch between list items using a button to change the ID in Javascript

I am trying to implement a floating navbar that appears after a button click and floats down from the top. The idea is that when the button is clicked, the navbar animates downward and then changes the button's id so that the next click triggers a dif ...

image rollovers for responsive pictures utilizing the picture element and srcset

Trying to find a way to implement an image rollover effect on the picture element within a responsive website. The big question is, can we apply an image rollover to the scrset attribute in the picture tag? An example of an img tag with a JavaScript roll ...

Using the symbols '&', '>', and '*' in the styling of React components

Below is the code snippet in question: const useStyles = makeStyles(theme => ({ row: { '& > *': { fontSize: 12, fontWeight: 'bold', color: 'rgba(33,34,34,0.5)', letterSpacing: 0.5, ...

JavaScript function that returns both a number and a word using regular expressions

Could anyone help me figure out why my code is now returning null when it used to find a match? I want it to search for a match in the string for 1 hour. var error = "null"; var str = "1 hour" var strCheck = str.match(/[1]\s[hour]\s/g); if(S ...

Troubleshooting issue with ng-change function in AngularJS

I have been working on developing a web application that includes two dropdown lists. My goal is to update the data in dropdown list 2 whenever there is a change in dropdown list 1. <tr> <td> State </td> <td> ...

Uncertain about how to handle JSON data

Currently developing a weather app for Android in Eclipse, I need to display weather icons at 3-hour intervals over a 24-hour period. Using the API from Utilizing to generate Java classes (I believe that's its purpose..) Here is the code snippet: ...

My AJAX requests do not include any custom headers being sent

I'm facing an issue with making an AJAX request from my client to my NodeJS/ExpressJS backend. After firing the request, my backend successfully receives it but fails to recognize the custom headers provided. For example: $.ajax({ type: " ...

Creating a dynamic two-player chess application using Django - requiring the player's chess board to automatically update whenever the opponent makes a move

I am looking for a solution where each player has their own webpage equipped with a Javascript chessboard GUI interface that allows them to click and drag pieces. The challenge is ensuring that when one player makes a move, the other player's chessboa ...

python Using urllib2 to retrieve JSON data

I need help retrieving a JSON object from a specific URL. I've provided the correct API key, but when I attempt to do the following: data=json.loads(a.read()) print data I encounter this error: Traceback (most recent call last): File "C:\Pyt ...

I need to inform users that this application is not accessible on devices with small screens

Showing this app on a small device is not supported, such as when the device width falls between 320px and 480px. ...

Encountering a Jackson Deserialization error when working with a data class in Kotlin

Having some trouble explaining the issue clearly, I decided to showcase the problem using code snippets in both Java and Kotlin for better clarity. The problem arises when I try to read JSON data and find that it is assigning a NULL value to a data bean&a ...

Forming a BoxBufferGeometry using the dimensions from Box3

I'm looking to generate a box mesh within a three.js scene, with the points of the box mesh matching the bounding box of an existing object in the scene. I attempted to create the box mesh from box3 using the method outlined below, but I'm not a ...

The form is refusing to submit even after using the "return false

Even after adding validation to the form, it still submits when the script returns false. The Form Submission <form action=payment.php method=POST name=UserForm id=UserForm onsubmit="return check(this); return false;"> Javascript Code function ch ...

JavaScript alert box

I'm fairly new to the world of web development, with knowledge in CSS & HTML and currently learning TypeScript. I'm attempting to create a message icon that opens and closes a notifications bar. Here's where I'm at so far: document.getE ...

Transfer the Vue query parameter from the current route to the router-link

Why is it so challenging to detect and pass query parameters in Vue components? I'm trying to access the router from my component, but nothing seems to be working. How can I achieve this? <router-link :to="{ path: '/', query: { myQue ...

The function is not operational while executing addEventListener

I'm encountering some bugs in my Angular 1.5 project with TypeScript. I'm trying to retrieve the scrollTop value from the .uc-card element. public container = document.querySelector(".uc-card"); In my $onInit, I have: public $onInit() { this ...

I am in need of a efficient loader for a slow-loading page on my website. Any recommendations on where to find one that works

I'm experiencing slow loading times on my website and I'm looking to implement a loader that will hide the page until all elements are fully loaded. I've tested several loaders, but they all seem to briefly display the page before the loader ...