Accessing name and id of object - Javascript - javascript

So i have this following object in Javascript, and I am interested in only id: '410467873518256138', name: 'element1'
How can i extract this information from the object?
I tried storing it in object and doing object.id or object.name but it prints nothing.
'410467873518256138' => Emoji {
guild:
Guild {
members: [Object],
channels: [Object],
roles: [Object],
presences: [Object],
available: true,
id: '410467289767346186',
name: 'emoji_set4',
icon: null,
splash: null,
region: 'singapore',
memberCount: 2,
large: false,
features: [],
applicationID: null,
afkTimeout: 300,
afkChannelID: null,
systemChannelID: '410467289767346188',
embedEnabled: undefined,
verificationLevel: 0,
explicitContentFilter: 0,
joinedTimestamp: 1517933748730,
ownerID: '352458321456005123',
_rawVoiceStates: Collection {},
emojis: [Object] },
id: '410467873518256138',
name: 'element1',
requiresColons: true,
managed: false,
animated: false,
_roles: [] },
Also kindly explain what this syntax is '410467873518256138' => Emoji {, cause generally we write variable = {} to define an object.

Related

MongoDB find() giving wrong object?

I am running a Mongo query from the Order database which aims to fetch the orders of a particular user by using his email. This is done using an API, but I am getting the complete object with some unnecessary details.
Code
I have written the following API in nextJS name myorders:
import Order from "../../models/Order";
import connectDB from "../../middleware/mongoose";
import jsonwebtoken from "jsonwebtoken";
const handler = async(req, res) => {
const token = req.body.token;
const data = jsonwebtoken.verify(token,process.env.JWT_SECRET);
console.log(data)
let mere_orders = Order.find({email: data.email})
console.log("mereorders12 = ", mere_orders)
res.status(200).json({mere_orders});
}
export default connectDB(handler);
And console.log("mereorders12 = ", mere_orders) gives me this:
mereorders12 = Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
_executionStack: null,
mongooseCollection: Collection {
collection: Collection { s: [Object] },
Promise: [Function: Promise],
modelName: 'Order',
_closed: false,
opts: {
autoIndex: true,
autoCreate: true,
schemaUserProvidedOptions: [Object],
capped: false,
Promise: [Function: Promise],
'$wasForceClosed': undefined
},
name: 'orders',
collectionName: 'orders',
conn: NativeConnection {
base: [Mongoose],
collections: [Object],
models: [Object],
config: {},
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object: null prototype],
_readyState: 1,
_closeCalled: undefined,
_hasOpened: true,
plugins: [],
id: 0,
_queue: [],
_listening: false,
_connectionString: 'mongodb://localhost:27017/chesswear',
_connectionOptions: [Object],
client: [MongoClient],
'$initialConnection': [Promise],
db: [Db],
host: 'localhost',
port: 27017,
name: 'chesswear'
},
queue: [],
buffer: false,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false
}
},
model: Model { Order },
schema: Schema {
obj: {
email: [Object],
orderId: [Object],
paymentInfo: [Object],
products: [Object],
address: [Object],
subtotal: [Object],
status: [Object]
},
paths: {
email: [SchemaString],
orderId: [SchemaString],
paymentInfo: [SchemaString],
products: [Mixed],
address: [SchemaString],
subtotal: [SchemaNumber],
status: [SchemaString],
_id: [ObjectId],
updatedAt: [SchemaDate],
createdAt: [SchemaDate],
__v: [SchemaNumber]
},
aliases: {},
subpaths: {},
virtuals: { id: [VirtualType] },
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: { initializeTimestamps: [Function (anonymous)] },
methodOptions: {},
statics: {},
tree: {
email: [Object],
orderId: [Object],
paymentInfo: [Object],
products: [Object],
address: [Object],
subtotal: [Object],
status: [Object],
_id: [Object],
updatedAt: [Function: Date],
createdAt: [Object],
__v: [Function: Number],
id: [VirtualType]
},
query: {},
childSchemas: [],
plugins: [ [Object], [Object], [Object], [Object], [Object] ],
'$id': 1,
mapPaths: [],
s: { hooks: [Kareem] },
_userProvidedOptions: { timestamps: true },
options: {
timestamps: true,
typeKey: 'type',
id: true,
_id: true,
validateBeforeSave: true,
read: null,
shardKey: null,
discriminatorKey: '__t',
autoIndex: null,
minimize: true,
optimisticConcurrency: false,
versionKey: '__v',
capped: false,
bufferCommands: true,
strictQuery: true,
strict: true,
pluralization: true
},
'$timestamps': { createdAt: 'createdAt', updatedAt: 'updatedAt' },
'$globalPluginsApplied': true,
_requiredpaths: [ 'status', 'subtotal', 'address', 'products', 'orderId', 'email' ]
},
op: 'find',
options: {},
_conditions: { email: 'mohit6#test.com' },
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection: NodeCollection {
collection: Collection {
collection: [Collection],
Promise: [Function: Promise],
modelName: 'Order',
_closed: false,
opts: [Object],
name: 'orders',
collectionName: 'orders',
conn: [NativeConnection],
queue: [],
buffer: false,
emitter: [EventEmitter]
},
collectionName: 'orders'
},
_traceFunction: undefined,
'$useProjection': true
}
But I should return order like this:
{
orders: [
{
"_id":"62693ae3f7fd0b7d87c8eb9c"},
"email":"mohit3#test.com",
"orderId":"1389629752594",
"paymentInfo":"No payment info",
"products":{...},
"address":"adasdklfasflka",
"subtotal":4,
"status":"Paid",
"createdAt":{"$date":"2022-04-27T12:45:23.352Z"},
"updatedAt":{"$date":"2022-04-27T12:45:23.352Z"},"__v":0
},
{
"_id":"62693ae3f7fd0b7d87c8eb9c"},
"email":"mohit3#test.com",
"orderId":"1389629752594",
"paymentInfo":"No payment info",
"products":{...},
"address":"adasdklfasflka",
"subtotal":14,
"status":"Paid",
"createdAt":{"$date":"2022-04-27T12:45:23.352Z"},
"updatedAt":{"$date":"2022-04-27T12:45:23.352Z"},"__v":0
}
]
}
Additionally this is the model schema of Order
const mongoose = require("mongoose");
const OrderSchema = new mongoose.Schema(
{
email: { type: String, required: true },
orderId: { type: String, required: true },
paymentInfo: { type: String, default: "No payment info" },
products: { type: Object, required: true },
address: { type: String, required: true },
subtotal: { type: Number, required: true },
status: { type: String, required: true, default: "Pending" },
},
{ timestamps: true }
);
export default mongoose.models.Order || mongoose.model("Order", OrderSchema);
Please help.
From Model.find(), it returns Query object.
Following the example, you need to execute the query asynchronously.
let mere_orders = await Order.find({email: data.email}).exec();
Or
let mere_orders = await Order.find({email: data.email});
As you are trying to return JSON as:
{
orders: [...]
}
You should return the response as below:
res.status(200).json({ orders: mere_orders });

Sequelize rounding id

I'm using Sequelize with SQLite on NodeJS. I have a User table in which I store IDs (16 chars long. Example: 795051544012783646). Whenever I query the DB for a specific user, it does something weird with it's ID:
user {
dataValues: {
id: 218062175636291600,
name: 'Raki',
balance: 0,
ap: 0,
objCount: 0
},
_previousDataValues: {
id: 218062175636291600,
name: 'Raki',
balance: 0,
ap: 0,
objCount: 0
},
uniqno: 1,
_changed: Set(0) {},
_options: {
isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [ 'id', 'name', 'balance', 'ap', 'objCount' ]
},
isNewRecord: false
}
The ID should be 218062175636291586, but it shows 218062175636291600. It's worth noting that the DB itself stores it as it is (it works perfectly).
What I tried
My User model declares IDs as INTEGERs, so I switched them to BIGINTs. Didn't work.

How to read through object of server roles Discord.js

I have the following code, which basically assigns a RoleManager object to the variable roles
var roles = receivedMessage.guild.roles;
console.log(roles['cache']);
Now, the log returns some mess that (partially) looks like this:
Collection [Map] {
'529502688183058443' => Role {
guild: Guild {
members: [GuildMemberManager],
channels: [GuildChannelManager],
roles: [RoleManager],
presences: [PresenceManager],
voiceStates: [VoiceStateManager],
deleted: false,
available: true,
id: '529502688183058443',
shardID: 0,
name: 'GuyDyamond Studios',
icon: '36e1f32f9fc98818872ca4583d50cc52',
splash: null,
discoverySplash: null,
region: 'us-east',
memberCount: 6,
large: false,
features: [],
applicationID: null,
afkTimeout: 300,
afkChannelID: null,
systemChannelID: '529502688183058445',
embedEnabled: undefined,
premiumTier: 0,
premiumSubscriptionCount: 0,
verificationLevel: 'MEDIUM',
explicitContentFilter: 'DISABLED',
mfaLevel: 0,
joinedTimestamp: 1600020773558,
defaultMessageNotifications: 'ALL',
systemChannelFlags: [SystemChannelFlags],
maximumMembers: 250000,
vanityURLCode: null,
vanityURLUses: null,
description: null,
banner: null,
rulesChannelID: null,
publicUpdatesChannelID: null,
preferredLocale: 'en-US',
ownerID: '423162345108275213',
emojis: [GuildEmojiManager]
},
id: '529502688183058443',
name: '#everyone',
color: 0,
hoist: false,
rawPosition: 0,
permissions: Permissions { bitfield: 104324673 },
managed: false,
mentionable: false,
deleted: false
},
'529672467200081922' => Role {
guild: Guild {
members: [GuildMemberManager],
channels: [GuildChannelManager],
roles: [RoleManager],
presences: [PresenceManager],
voiceStates: [VoiceStateManager],
deleted: false,
available: true,
id: '529502688183058443',
shardID: 0,
name: 'GuyDyamond Studios',
icon: '36e1f32f9fc98818872ca4583d50cc52',
splash: null,
discoverySplash: null,
region: 'us-east',
memberCount: 6,
large: false,
features: [],
applicationID: null,
afkTimeout: 300,
afkChannelID: null,
systemChannelID: '529502688183058445',
embedEnabled: undefined,
premiumTier: 0,
premiumSubscriptionCount: 0,
verificationLevel: 'MEDIUM',
explicitContentFilter: 'DISABLED',
mfaLevel: 0,
joinedTimestamp: 1600020773558,
defaultMessageNotifications: 'ALL',
systemChannelFlags: [SystemChannelFlags],
maximumMembers: 250000,
vanityURLCode: null,
vanityURLUses: null,
description: null,
banner: null,
rulesChannelID: null,
publicUpdatesChannelID: null,
preferredLocale: 'en-US',
ownerID: '423162345108275213',
emojis: [GuildEmojiManager]
},
Now, I've literally tried everything, but I can't seem to iterate over the object roles. I've tried a forEach function, a for...in... loop, etc etc, nothing. Additionally, I'm trying to get the name of each role and put it in an array, but I can't seem to get the name parameter. Any help on how to do this?
If all you need is the names, you can use Array.prototype.map:
console.log(
recievedMessage.guild.roles.cache.map((role) => role.name)
);
Example result:
['Admin', 'Mod', 'VIP', 'Member', 'Muted', '#everyone']
To iterate a function through every role, use:
recievedMessage.guild.roles.cache.forEach((role) => {
console.log(role.id);
});

How to get user-roles with sequelize?

I have a realtion like this:
in my resolver I am fetching the enteties like this:
users: async () => {
const users = await db.user.findAll({
include: [
{
model: db.userroles,
include: [
{
model: db.roles,
attributes: ['Name'],
},
],
},
],
});
I log what I get from the db:
console.log('users are', users[0].dataValues.userroles[0].dataValues.role.Name); // logs "users are developer"
Which shows me that the correct roles are fetched.
My graphql schema:
type user {
Id: ID!
Email: String
RoleId: Int!
Password: String
ChangedPassword: Boolean
WeddingId: Int!
AttendantId: Int
role: [roles!]
}
type roles {
Id: ID!
Name: String!
}
In the playground I am sending this:
{users
{role
{Name}}
}
result:
"data": {
"users": [
{
"role": null
}
]
}
}
When I log the entire user object that I get back from the db:
users are userroles {
dataValues:
{ UserId: 1,
RoleId: 1,
role:
roles {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
isNewRecord: false } },
_previousDataValues:
{ UserId: 1,
RoleId: 1,
role:
roles {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
isNewRecord: false } },
_changed: {},
_modelOptions:
{ timestamps: false,
validate: {},
freezeTableName: true,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [],
name: { plural: 'userroles', singular: 'userrole' },
omitNull: false,
tableName: 'userroles',
sequelize:
Sequelize {
options: [Object],
config: [Object],
dialect: [MysqlDialect],
queryInterface: [QueryInterface],
models: [Object],
modelManager: [ModelManager],
connectionManager: [ConnectionManager],
importCache: [Object] },
hooks: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
include: [ [Object] ],
includeNames: [ 'role' ],
includeMap: { role: [Object] },
includeValidated: true,
raw: true,
attributes: undefined },
isNewRecord: false,
role:
roles {
dataValues: { Name: 'Developer' },
_previousDataValues: { Name: 'Developer' },
_changed: {},
_modelOptions:
{ timestamps: false,
validate: {},
freezeTableName: true,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [],
name: [Object],
omitNull: false,
tableName: 'roles',
sequelize: [Sequelize],
hooks: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
include: undefined,
includeNames: undefined,
includeMap: undefined,
includeValidated: true,
raw: true,
attributes: [Array] },
isNewRecord: false } }
I am getting the roles I just can't figure out how to present them?
I think that the issue is in my resolver that I am missing yet another set of includes but I cant figure out how to write it.
user and roles have a many-to-many relationship with userRoles as the junction table. If you have not already, should should define this relationship on user:
user.belongsToMany(roles, { through: userRoles })
This will let you include roles directly:
const users = await db.user.findAll({
include: [
db.roles,
],
});
After posting I noticed some issues in my schema.
I changed my schema to:
type roles {
Id: ID!
Name: String!
}
type userroles {
RoleId: ID!
UserId: ID!
role: roles
}
type user {
Id: ID!
Email: String
RoleId: Int!
Password: String
ChangedPassword: Boolean
WeddingId: Int!
AttendantId: Int
userroles: [userroles!]
}
playground:
{users
{userroles
{role
{Name}}}
}
result:
"data": {
"users": [
{
"userroles": [
{
"role": {
"Name": "Developer"
}
}
]
}
]
}
}
The answer stared me right in the face but I was focused on the code in the resolver.
Leaving this question in case someone has another way of doing this.

Get random Discord user

Im creating a bot that taggs a random user, but im having some difficulties.
How can I get a random user? Im currently doing this:
let usersCount = message.guild.memberCount;
let users = Array.from(message.guild.members);
let randomNumber = Math.floor(Math.random() * usersCount);
let randomUser = users[randomNumber];
console.log(randomUser);
But its returning this, with the whole guild:
[ '208045530369097728', GuildMember {
guild:
Guild {
members: [Object],
channels: [Object],
roles: [Object],
presences: [Object],
deleted: false,
available: true,
id: '4481898438608814093132',
name: 'bot test',
icon: '21cddd6a700aaff9b9ccb0c2c1b8de5e',
splash: null,
region: 'brazil',
memberCount: 71,
large: false,
features: [],
applicationID: null,
afkTimeout: 300,
afkChannelID: '448206219711217674',
systemChannelID: null,
embedEnabled: undefined,
verificationLevel: 0,
explicitContentFilter: 0,
mfaLevel: 0,
joinedTimestamp: 1535857830448,
defaultMessageNotifications: 'ALL',
ownerID: '2013795851090283612',
_rawVoiceStates: Collection {},
emojis: [Object] },
user:
User {
id: '2180145503619097728',
username: 'xxxx!',
discriminator: '4198',
avatar: 'a1fb0d1c273a18acc69fa9f796a8c7d7',
bot: false,
lastMessageID: null,
lastMessage: null },
joinedTimestamp: 1526933713197,
_roles:
[ '44811902750147915532',
'45769217147885815476',
'47113897343090168840' ],
serverDeaf: false,
serverMute: false,
selfMute: undefined,
selfDeaf: undefined,
voiceSessionID: undefined,
voiceChannelID: undefined,
speaking: false,
nickname: 'xxxx',
lastMessageID: null,
lastMessage: null,
deleted: false } ]
How can I get the user and tag him?
I already tried randomUser.user, returns undefined. I have no idea
Solved
var user = message.guild.members.random();
console.log(`${user.user}`);
let randomPer = message.guild.members.cache.random().user;
message.channel.send(`${randomPer}`)
This will mention a random user from your guild.

Categories