MongoDB not saving correct ID | Discord.js 13 - javascript

So this may just be me being stupid and forgetting a semicolon or something, but I can't seem to resolve this. For my ticket command, I make it so when someone uses the command /ticketsetup and it saves the data of the inputted channels as ID's to then be referenced later. But for some reason, one of them just saves a completely random ID that isn't related to the inputted channel (Transcript)
const {MessageEmbed, CommandInteraction, MessageActionRow, MessageButton} = require('discord.js')
const DB = require('../../Structures/Schemas/TicketSetup')
module.exports = {
name: "ticketsetup",
usage: "/ticketsetup (Admin only)",
description: "Setup your ticketing message.",
permission: "ADMINISTRATOR",
options: [
{
name: "channel",
description: "Select the ticket creation channel.",
required: true,
type: "CHANNEL",
channelTypes: ["GUILD_TEXT"]
},
{
name: "category",
description: "Select the ticket channel's category.",
required: true,
type: "CHANNEL",
channelTypes: ["GUILD_CATEGORY"]
},
{
name: "transcripts",
description: "Select the transcripts channel.",
required: true,
type: "CHANNEL",
channelTypes: ["GUILD_TEXT"]
},
{
name: "handlers",
description: "Select the ticket handler's role.",
required: true,
type: "ROLE"
},
{
name: "description",
description: "Set the description of the ticket creation channel.",
required: true,
type: "STRING"
}
],
/**
*
* #param {CommandInteraction} interaction
*/
async execute(interaction) {
const {guild, options} = interaction
try {
const Channel = options.getChannel("channel")
const Category = options.getChannel("category")
const Transcripts = options.getChannel("transcripts")
const Handlers = options.getRole("handlers")
const Description = options.getString("description")
await DB.findOneAndUpdate({GuildID: guild.id},
{
ChannelID: Channel.id,
Category: Category.id,
Transcripts: Transcripts.id,
Handlers: Handlers.id,
Everyone: guild.id,
Description: Description,
},
{
new: true,
upsert: true
}
);
const Embed = new MessageEmbed().setAuthor({
name: guild.name + " | Ticketing System",
iconURL: guild.iconURL({dynamic: true})
})
.setDescription(Description)
.setColor("#36393f")
const Buttons = new MessageActionRow()
Buttons.addComponents(
new MessageButton()
.setCustomId("ticket")
.setLabel("Create Ticket!")
.setStyle("PRIMARY")
.setEmoji("🎫")
)
await guild.channels.cache.get(Channel.id).send({embeds: [Embed], components: [Buttons]})
interaction.reply({content: "Done", ephemeral: true})
} catch (err) {
const ErrEmbed = new MessageEmbed().setColor("RED")
.setDescription(`\`\`\`${err}\`\`\``)
interaction.reply({embeds: [ErrEmbed]})
}
}
}
Schema Model:
const {model, Schema} = require('mongoose')
module.exports = model("TicketSetup", new Schema({
GuildID: String,
Channel: String,
Category: String,
Transcripts: String,
Handlers: String,
Everyone: String,
Description: String,
}))

Related

Undefined value

i have a problem
i entered Unturned or any other game but in output it says about other game
const { ApplicationCommandType } = require('discord.js');
const fetch = require("node-fetch");
const pop = require('popcat-wrapper')
module.exports = {
name: 'steam',
description: "get info about games",
type: ApplicationCommandType.ChatInput,
cooldown: 3000,
options: [
{
name: 'gameinfo',
description: 'get info about a game',
type: 1,
options: [
{
name: 'game',
description: 'Game name',
type: 3,
required: true
}
]
}
],
run: async (client, interaction) => {
const game = interaction.options.get('game')
const gameinfo = await pop.steam(game)
console.log(gameinfo)
}
}
what i got (this is not that game that i entered)
{
type: 'game',
name: 'Touhou Seirensen ~ Undefined Fantastic Object.',
thumbnail: 'https://cdn.akamai.steamstatic.com/steam/apps/1100160/capsule_231x87.jpg?t=1591411698',
description: 'アレは何だ? 鳥か? 妖精か? 謎に満ちた未確認幻想物体が、君を未知の世界に誘う! ファンタスティックでレトロな弾幕シューティング幻想',
website: 'http://www16.big.or.jp/~zun/',
banner: 'https://cdn.akamai.steamstatic.com/steam/apps/1100160/header.jpg?t=1591411698',
developers: [ '上海アリス幻樂団' ],
publishers: [ 'Mediascape Co., Ltd.' ],
price: '12,49€'
}
I'm new to Javascript. And English its not my main language sorry for errors if there's any
i fix it
i added .value:
const game = interaction.options.get("game").value;

MongoDB - how do I deep populate, an already populated field that has a reference to the schema it is in?

So I am having the following problem, I have a comments schema, which has a field called Replies and it is pointing toward the comment schema. The problem is that whenever I try to populate the following schema, everything except for the replies gets populated. Why is that happening, how do I fix it?
Comment Schema:
const {Schema, model} = require('mongoose')
const { ObjectId } = require('mongodb');
const commentSchema = new Schema({
Author:
{
type: ObjectId,
required: true,
ref: 'user'
},
Content:
{
type: String,
required: true
},
Likes:{
type: [ObjectId],
ref: 'user'
},
Replies: [this]
})
let comment = model('comment', commentSchema)
module.exports = comment
And that is how I populate the posts model:
let allPosts = await postModel
.find({})
.populate('Author Comments')
.populate(
(
{
path: 'Comments',
populate:[
{path: 'Author'}
]
},
{
path: 'Comments.Replies',
populate:[
{path: 'Author'}
]
}
)
)
and this is my post model, referenced in the previous code sample:
const {Schema, model} = require('mongoose')
const { ObjectId } = require('mongodb');
const postSchema = new Schema({
Author:
{
type: ObjectId,
required: true,
ref: 'user'
},
Content:
{
type: String,
required: true
},
Shares:{
type: [ObjectId],
ref: 'post'
},
Likes:{
type: [ObjectId],
ref: 'user'
},
Comments:{
type: [ObjectId],
ref: 'comment'
}
})
let post = model('post', postSchema)
module.exports = post

How to add multiple items in model

I have a model called "list" where I have to put several items in it. But I made a code that can put only one item in a list. Can anyone help me solve this?
My model:
const mongoose = require('mongoose');
const { itemSchema } = require('./item.js');
const { shopSchema } = require('./shop.js');
const listSchema = mongoose.Schema({
name: { type: String, required: true },
created: { type: Date, required: true, unique: true },
updated: { type: Date },
items: [itemSchema],
shop: [shopSchema]
});
module.exports.ListData = mongoose.model("listData", listSchema);
module.exports.listSchema = listSchema;
itemSchema:
const mongoose = require('mongoose');
const categSchema = require("./category.js")
const itemSchema = mongoose.Schema({
name: { type: String, required: true },
created: { type: Date, required: true, unique: true },
category: [categSchema.categorySchema],
quantity: { type: Number, required: true }
});
module.exports.ItemData = mongoose.model("itemData", itemSchema);
module.exports.itemSchema = itemSchema;
How do I make "items:" to recieve multiple items, not just one? I am using mongodb for this project. Thanks!
Your items already accepts multiple items. Is this not what you want? I tested with this little experiment:
import connect from './db.js';
import mongoose from 'mongoose';
// this just connects to mongodb
await connect();
const itemSchema = mongoose.Schema({
name: { type: String, required: true }
});
const ItemData = mongoose.model("itemData", itemSchema);
const listSchema = mongoose.Schema({
name: { type: String, required: true },
items: [itemSchema]
});
const ListData = mongoose.model("listData", listSchema);
await ListData.deleteMany({});
// create items
await ItemData.create({ name: "potato" });
await ItemData.create({ name: "tomato" });
await ItemData.create({ name: "kitten" });
const items = await ItemData.find({});
await ItemData.deleteMany({});
// create list
await ListData.create({
name: "Stuff i luv",
items
});
// get inserted lists
const q = ListData.find();
q.select("-__v -_id -items.__v -items._id");
const ld = await q.exec();
// print results
console.log(JSON.stringify(ld));
// result is
[{
"name":"Stuff i luv",
"items":[{"name":"potato"},{"name":"tomato"},{"name":"kitten"}]
}]

How do I specify options for commands?

I want to specify choices for an option for my command in Discord.js. How do I do that?
The command:
module.exports = {
name: 'gifsearch',
description: 'Returns a gif based on your search term.',
options: [{
name: 'type',
type: 'STRING',
description: 'Whether to search for gifs or stickers.',
choices: //***this is the area where I have a question***
required: true
},
{
name: 'search_term',
type: 'STRING',
description: 'The search term to use when searching for gifs.',
required: true,
}],
async execute(interaction) {
let searchTerm = interaction.options.getString('search_term')
const res = fetch(`https://api.giphy.com/v1/gifs/search?q=${searchTerm}&api_key=${process.env.giphyAPIkey}&limit=1&rating=g`)
.then((res) => res.json())
.then((json) => {
if (json.data.length <= 0) return interaction.reply({ content: `No gifs found!` })
interaction.reply({content: `${json.data[0].url}`})
})
},
};
I have read the discord.js documentation/guide and I know about the .addChoice() method, but it doesn't look like that will be compatible with my bot's current code.
The discord.js api describes this as ApplicationCommandOptionChoices.
So you basically just insert an array of this in your choices.
module.exports = {
...
choices: [
{
name: "name to display",
value: "the actual value"
},
{
name: "another option",
value: "the other value"
}
]
...
};

Try to populate in mongoose and it doesn't work (nodejs)

i Make mini cart with Product and user Auth, Evereting work perfect but whan i try to make a route that pickup all the product from the user and view them in specific page and it not work for me.
it returns the user but not the product.
UserSchema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
product: {
type: [mongoose.Schema.Types.ObjectId],
ref: "product"
},
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
address: {
type: String,
required: true
},
password: {
type: String,
required: true
},
data: {
type: Date,
default: Date.now
}
});
module.exports = User = mongoose.model("user", UserSchema);
ProductScheama
const mongoose=require('mongoose');
const ProductSchema = new mongoose.Schema({
name:{
type:String,
required:true,
unique:true
},
description:{
type:String,
},
price:{
type:Number,
required:true
},
quantity:{
type:Number,
required:true
},
data:{
type:Date,
default:Date.now
}
})
module.exports=Product=mongoose.model('product',ProductSchema)
I am trying to create a function that gives me the name, price and description of the product and it fails.
my router:
router.get("/products/:id", auth, async (req, res) => {
try {
let pro = await User.find({ product: req.params.id }).populate("product", [
"name",
"price",
"description"
]);
if (!pro) {
return res.json({ msg: "This user not have products to show" });
}
res.json(pro);
} catch (err) {
console.error(err.message);
res.status(500).send("Server errors");
}
});
result from Postman:
[
{
"product": [],
"_id": "5d5bfb96963ca600ec412bca",
"name": "Anonny Annon",
"email": "Annony#gmail.com",
"address": "Israel",
"password": "$2a$10$gESTIaBVifzhRDR2zOKsw.Q79gCT07IK2VnDoyT2oU5htqfBuAj8W",
"data": "2019-08-20T13:54:30.267Z",
"__v": 0
}
]
I think product should be defined this way :
product: [{
type: mongoose.Schema.Types.ObjectId,
ref: "product"
}]
instead of type: [mongoose.Schema.Types.ObjectId]
Solution found here

Categories

Resources