Node.js caught error undefined but defined - javascript

I have been working on a bot for 12 days now and I need to upgrade to v12. Everything was going smoothly until I tried a command that will give a specified role to a mentioned user.
I have 2 variables. One is a role variable that the user has specified and the member variable (which is equaled to message.guild.members.get(args[0])).
The code looks like this:
let Member = message.mentions.members.first() || message.guild.members.get(arguments[0]);
if (!Member) return message.channel.send("Error: Either the member does not exist or you haven't put the member to give the role to!");
let role = message.guild.roles.cache.some(r => r.name === arguments[1]) || message.guild.roles.cache.some(r => r.id === arguments[1]) || message.mentions.roles.first();
if (!role) return nessage.channel.send("Error: Please provide a valid role!");
// if (role === "undefined") {
// let role = message.guild.roles.cache.some(r => r.name === arguments[1]) || message.guild.roles.cache.some(r => r.id === arguments[1]) || message.mentions.roles.first();
// }
if (Member.roles.cache.has(role.id)) {
return message.channel.send("Error: The mentioned user already has that role!");
} else {
let role = message.guild.roles.cache.some(r => r.name === arguments[1]) || message.guild.roles.cache.some(r => r.id === arguments[1]) || message.mentions.roles.first();
console.log(message);
console.log("role" + role);
Member.roles.add(role.id).catch(e => console.log("Error: " + e.message));
}
The code looked fine to me and expected it to work, but then I got an error in the console. It doesn't say what variable is not defined, it just says it's undefined.
I tried checking if the role variable is undefined, but I commented out since it didn't work. Then, I have let it print the message and check if the role is undefined. The role variable is fine. The message variable is fine. Even the Member variable is fine.
I use the latest Node.js.
Here's the console log:
Message {
channel: TextChannel {
type: 'text',
deleted: false,
id: '729663938148565134',
name: 'general',
rawPosition: 0,
parentID: '729663938148565132',
permissionOverwrites: Collection [Map] {},
topic: 'Beware, there will be a lot of mentions.',
nsfw: undefined,
lastMessageID: '733951355240316948',
rateLimitPerUser: 0,
lastPinTimestamp: 1594845448699,
guild: Guild {
members: [GuildMemberManager],
channels: [GuildChannelManager],
roles: [RoleManager],
presences: [PresenceManager],
voiceStates: [VoiceStateManager],
deleted: false,
available: true,
id: '729663937557168181',
shardID: 0,
name: 'Bot Testing',
icon: null,
splash: null,
region: 'europe',
memberCount: 6,
large: false,
features: [],
applicationID: null,
afkTimeout: 300,
afkChannelID: null,
systemChannelID: '729663938148565134',
embedEnabled: undefined,
premiumTier: 0,
premiumSubscriptionCount: 0,
verificationLevel: 'MEDIUM',
explicitContentFilter: 'DISABLED',
mfaLevel: 0,
joinedTimestamp: 1594035922599,
defaultMessageNotifications: 'ALL',
systemChannelFlags: [SystemChannelFlags],
vanityURLCode: null,
description: null,
banner: null,
rulesChannelID: null,
publicUpdatesChannelID: null,
ownerID: '402159567200583680',
emojis: [GuildEmojiManager]
},
messages: MessageManager {
cacheType: [Function: LimitedCollection],
cache: [LimitedCollection [Map]],
channel: [Circular]
},
_typing: Map { '402159567200583680' => [Object] }
},
deleted: false,
id: '733951355240316948',
type: 'DEFAULT',
content: '>giveRole <#!655895332722442282> Mod',
author: User {
id: '402159567200583680',
bot: false,
username: '🎁🎄KFM🎄🎁',
discriminator: '3147',
avatar: '5f322e4ab3ec14e9fa83e1c77d8bb36d',
lastMessageID: '733951355240316948',
lastMessageChannelID: '729663938148565134',
flags: UserFlags { bitfield: 0 }
},
pinned: false,
tts: false,
nonce: '733951341017169920',
system: false,
embeds: [],
attachments: Collection [Map] {},
createdTimestamp: 1595058039246,
editedTimestamp: null,
reactions: ReactionManager {
cacheType: [Function: Collection],
cache: Collection [Map] {},
message: [Circular]
},
mentions: MessageMentions {
everyone: false,
users: Collection [Map] { '655895332722442282' => [User] },
roles: Collection [Map] {},
_members: Collection [Map] { '655895332722442282' => [GuildMember] },
_channels: null,
crosspostedChannels: Collection [Map] {}
},
webhookID: null,
application: null,
activity: null,
_edits: [],
flags: MessageFlags { bitfield: 0 },
reference: null
}
roletrue
Error: undefined
Thanks in advance!
EDIT: It looks like the role.id is undefined. I will try to see how to fix that.

I think problem with this part of code
console.log("role" + role); // true
Member.roles.add(role.id).catch(e => console.log("Error: " + e.message));
You trying add undefined in roles, because:
const roleId = (true).id;
console.log(roleId); //undefined
Your got your Boolean from some function which always return true or false, try change this to find
try add some id like 733951355240316948.
I dont know how looks role.id, but role must be Object
for example:
{
id:'asdasdawe3534536456',
// other fields
}
You need find what expect .add function in Member.roles.add

Related

Knex.js return inserted record ID

I am inserting a note into the quoteNotes table. When I insert it and console log the res. it doesn't give me a record of the inserted note.
router.post('/:id/notes', (req, res) => {
const {id} = req.params;
const note = req.body;
note.quote_id = id
// if(note.note === "") return res.status(422)
// .json({message: 'Note cannot be empty'});
Quotes.addNote(note).then((quoteNote) => {
console.log(quoteNote)
res.status(200).json(quoteNote);
});
});
console.log =>
Result {
command: 'INSERT',
rowCount: 1,
oid: 0,
rows: [],
fields: [],
_parsers: undefined,
_types: TypeOverrides {
_types: {
getTypeParser: [Function: getTypeParser],
setTypeParser: [Function: setTypeParser],
arrayParser: [Object],
builtins: [Object]
},
text: {},
binary: {}
},
RowCtor: null,
rowAsArray: false
}
Figured it out.
needed to add .returning('id') to the query.
function addNote(data) {
return db('quote_notes')
.insert(data)
.returning('id');
}
In my case with mysql, the await insert({...}) returned an array with an id as a single element. And by using returning('id') I got an error saying it's not supported for mysql.

How to access values in "msg.guild.members.fetch()"

This is the piece of important code -
const Members = msg.guild.members.fetch();
console.log(Members)
I want to access the variables in "Members" and also want to know what data type it is (object,array,etc.)
This is the log -
Promise {
Collection [Map] {
'518759221098053634' => GuildMember {
guild: [Guild],
user: [User],
joinedTimestamp: 1595386815939,
lastMessageID: null,
lastMessageChannelID: null,
premiumSinceTimestamp: null,
deleted: false,
_roles: [Array],
nickname: null
},
'680036979106512914' => GuildMember {
guild: [Guild],
user: [User],
joinedTimestamp: 1594698809775,
lastMessageID: null,
lastMessageChannelID: null,
premiumSinceTimestamp: null,
deleted: false,
_roles: [Array]
},
'717347622532153396' => GuildMember {
guild: [Guild],
user: [User],
joinedTimestamp: 1595919969136,
lastMessageID: '738997364949254154',
lastMessageChannelID: '735330127944220725',
premiumSinceTimestamp: null,
deleted: false,
_roles: [Array],
nickname: null
},
'730309712133881916' => GuildMember {
guild: [Guild],
user: [User],
joinedTimestamp: 1594954679836,
lastMessageID: null,
lastMessageChannelID: null,
premiumSinceTimestamp: null,
deleted: false,
_roles: [Array],
nickname: null
},
'730624908748521613' => GuildMember {
guild: [Guild],
user: [User],
joinedTimestamp: 1594698780260,
lastMessageID: null,
lastMessageChannelID: null,
premiumSinceTimestamp: null,
deleted: false,
_roles: [Array],
nickname: null
},
'738658236957458472' => GuildMember {
guild: [Guild],
user: [ClientUser],
joinedTimestamp: 1596183671593,
lastMessageID: '738997347387965531',
lastMessageChannelID: '735330127944220725',
premiumSinceTimestamp: null,
deleted: false,
_roles: [Array],
nickname: null
}
}
}
How do you store, for example, the user ID in this line:
'518759221098053634' => GuildMember {
I think there is one duplicate of this question, but i think the solutions there are outdated or for a different language.
Guild.members.fetch() is a Promise that will return:
A GuildMember if you provide a UserResolvable as the first parameter.
A Collection containing all the members in the guild if you don't provide anything as the first parameter.
message.guild.members.fetch("UserID").then(member => {
// This will return a single GuildMember object, if found.
console.log(`Found ${member.user.tag}. They are ${member.presence.status}.`);
}).catch(e => console.log("Couldn't fetch the member."));
// This will return a Collection containing all members in the Guild.
message.guild.members.fetch().then(members => {
// To store the user id(s) you can map the Collection by ID:
const IDs = members.map(user => user.id);
// --> ["UserID", "UserID", "UserID", "UserID"]
// To store certain id(s) you can use the filter method of Collection:
const OnlineMembers = members.filter(member => member.presence.status == "online");
}).catch(e => console.log("Couldn't fetch members."));
References:
Collection
GuildMember
Guild
GuildMemberManager
Promise

Sequelize .set error, .set is not a function

I am trying to set up a belongsTo and hasMany association which seems to be working, but when I run .set I am getting the error fighterData.setUsers is not a function. The dialect is mySql. Here is my code:
Fighters.belongsTo(Users)
Users.hasMany(Fighters);
Users.sync()
Fighters.sync()
//creates the table if it doesn't exist
const insertFighter = function(obj, sessId) {
return Fighters.create(obj, {returning: true}).then((fighterData) => {
//console.log('inserted a fighter \n', fighterData);
return Users.findOne({
where: {
id: sessId
}
}).then((userData) => {
//console.log('fighterData in findOne promise \n', fighterData)
return fighterData.setUsers(userData)
}).then((success)=> {
console.log('user fighter join success')
return
}).catch((err)=> {
console.log('user fighter join error \n', err)
return
})
}).catch((err)=> {
console.log('error inserting fighter \n', err);
})
}
The error that's logging is user fighter join error.
interestingly, userData.setFighters(fighterData) works successfully, but that is not what I need
EDIT
This is what fighterData is:
fighterData in findOne promise
Fighters {
dataValues:
{ id: 7,
name: 'Gilbert Burns',
image:
'https://www.sherdog.com/image_crop/200/300/_images/fighter/20140806063215_IMG_8432.JPG',
next_opponent: 'Kamaru Usman',
next_fight: 'July 11, 2020 ',
style: 'mma',
updatedAt: 2020-06-17T06:00:40.368Z,
createdAt: 2020-06-17T06:00:40.368Z },
_previousDataValues:
{ name: 'Gilbert Burns',
image:
'https://www.sherdog.com/image_crop/200/300/_images/fighter/20140806063215_IMG_8432.JPG',
next_opponent: 'Kamaru Usman',
next_fight: 'July 11, 2020 ',
style: 'mma',
id: 7,
createdAt: 2020-06-17T06:00:40.368Z,
updatedAt: 2020-06-17T06:00:40.368Z,
UserId: undefined },
_changed:
{ name: false,
image: false,
next_opponent: false,
next_fight: false,
style: false,
id: false,
createdAt: false,
updatedAt: false,
UserId: false },
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: false,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [],
name: { plural: 'Fighters', singular: 'Fighter' },
omitNull: false,
sequelize:
Sequelize {
options: [Object],
config: [Object],
dialect: [MysqlDialect],
queryInterface: [QueryInterface],
models: [Object],
modelManager: [ModelManager],
connectionManager: [ConnectionManager],
importCache: {} },
hooks: {} },
_options:
{ isNewRecord: true,
_schema: null,
_schemaDelimiter: '',
attributes: undefined,
include: undefined,
raw: undefined,
silent: undefined },
isNewRecord: false }
This is returned from entering one fighter's information into the database.
The problem is with the naming of your models.
Sequelize expects your models to be named in singular form (User instead of Users), so it's getting confused with what it should name the generated setter and getter methods for your association.
If you try fighterData.setUser(userData) instead of fighterData.setUsers(userData), it should work.
If you you want to use setUsers instead, you will have to make adjustments to your model to tell Sequelize to use Users as the singular form of User:
Users.init({
sessId: Sequelize.STRING
}, {
sequelize: sequelize,
name: {
singular: 'users'
}
});
You can overwrite the plural form the same way as well.
You can read more about this here: Sequelize naming strategy

Discord bot, how to get all connected "guilds/servers"

I'm trying to use client.guilds , but it just seems to return this really weird object that I have no idea how to parse.
Object:
GuildManager {
cacheType: [Function: Collection],
cache: Collection(1) [Map] {
'11111111111111111' => Guild {
members: [GuildMemberManager],
channels: [GuildChannelManager],
roles: [RoleManager],
presences: [PresenceManager],
voiceStates: [VoiceStateManager],
deleted: false,
available: true,
id: '1111111111111111111',
shardID: 0,
name: 'My Server Name',
icon: '11111111111111111111111111111',
splash: null,
region: 'us-west',
memberCount: 46,
large: false,
features: [],
applicationID: null,
afkTimeout: 300,
afkChannelID: null,
systemChannelID: null,
embedEnabled: undefined,
premiumTier: 0,
premiumSubscriptionCount: 0,
verificationLevel: 'NONE',
explicitContentFilter: 'DISABLED',
mfaLevel: 0,
joinedTimestamp: 1590266012969,
defaultMessageNotifications: 'ALL',
systemChannelFlags: [SystemChannelFlags],
vanityURLCode: null,
description: null,
banner: null,
rulesChannelID: null,
publicUpdatesChannelID: null,
ownerID: '111111111111111111',
emojis: [GuildEmojiManager]
}
}
}
I just simply don't know how to parse this to get the name of the servers I'm connected to. Right now I'm only connected to one server but in the future there will be more, I just want to ideally be able to say:
client.guilds.forEach(server => {
console.log(guild.name+" id: "+guild.id);
});
This object is basic collection you can iterate over.
client.guilds.forEach(server => {
console.log(server.name + " (id: " + server.id + ")");
});
Turns out I had to reference the cache object:
client.guilds.cache.forEach(server => {
console.log(server.name + " id: " + server.id);
});

Using Object.assign() on a doc returned from a mongoose Model query

When using Object.assign() on a document returned from a mongoose model query, the object returns extraneous data which I do not want, and to get the actual document data I need to use doc._doc - whereas without using Object.assign() I have immediate access to the document data (not inside ._doc).
UserModel.findOne(query, function(err, doc){
//this outputs my document data just fine
console.log(doc);
//this outputs extraneous data, assigning someProp not to my document data,
//but to the outer object.
console.log(Object.assign({}, doc, { someProp: true});
})
Here is the result of console.log(doc):
{
_id: 5ab5df214869bc4bfc059fed,
userID: 0,
verified: false,
verificationCode: 'vC_10a89847-f640-43fc-94cc-8ea532f5e05c',
email: 'ee#ee.ee',
createdAt: 2018-03-24T05:16:17.508Z,
updatedAt: 2018-03-25T16:57:30.101Z,
__v: 0
}
And here is the result of console.log(Object.assign({}, doc, { someProp: true });
{ '$__':
InternalCache {
strictMode: true,
selected: {},
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: undefined,
version: undefined,
getters: {},
_id: 5ab5df214869bc4bfc059fed,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths: StateMachine { paths: [Object], states: [Object], stateNames: [Array] },
pathsToScopes: {},
ownerDocument: undefined,
fullPath: undefined,
emitter: EventEmitter { domain: null, _events: {}, _eventsCount: 0, _maxListeners: 0 },
'$options': true },
isNew: false,
errors: undefined,
_doc:
{
_id: 5ab5df214869bc4bfc059fed,
userID: 0,
verified: false,
verificationCode: 'vC_10a89847-f640-43fc-94cc-8ea532f5e05c',
email: 'ee#ee.ee',
createdAt: 2018-03-24T05:16:17.508Z,
updatedAt: 2018-03-25T16:57:30.101Z,
__v: 0 },
'$init': true,
someProp: true }
My question is, why do I need to use doc._doc inside and after using doc = Object.assign({}, doc._doc, { someProp: true }) to access my document data, but I could access the data properties without ._doc before using doc = Object.assign(...)?

Categories