when a user login and clicks the cart button i want to see the products which added by the user in my console. in my cart collection there is some documents which contain userid and products id.so when a user clicks the cart link on the navbar i want to see the products which added to the cart by the user in my console but instead of this am getting this error.this is the first time i using aggregate in monogodb
getCartProduct in usehelpers.js
getCartProducts: userId => {
return new Promise(async (resolve, reject) => {
let CartItems = await db
.get()
.collection(Collection.CART_COLLECTIONS)
.aggregate([
{
$match: { user: objectId(userId) },
},
{
$lookup: {
from: Collection.PRODUCT_COLLECTIONS,
let: { prodList:'$products' },
pipeline: [
{
$match: {
$expr: {
$in: ['$_id', '$$prodList'],
},
},
},
],
as: 'CartItems',
},
},
])
.toArray();
resolve(CartItems);
});
},
};
arguments passed from user.js
router.get('/cart',verifyLogin,async(req,res)=>{
let products = await userHelpers.getCartProducts(req.session.user._id)
console.log(products);
res.render('user/cart')
})
console error
MongoServerError: PlanExecutor error during aggregation :: caused by :: $in requires an array as a second argument, found: objectId
at Connection.onMessage (C:\Users\krish\OneDrive\Desktop\project mern stack\webdev-challenge\node_modules\mongodb\lib\cmap\connection.js:210:30)
at MessageStream.<anonymous> (C:\Users\krish\OneDrive\Desktop\project mern stack\webdev-challenge\node_modules\mongodb\lib\cmap\connection.js:63:60)
at MessageStream.emit (events.js:400:28)
at processIncomingData (C:\Users\krish\OneDrive\Desktop\project mern stack\webdev-challenge\node_modules\mongodb\lib\cmap\message_stream.js:132:20)
at MessageStream._write (C:\Users\krish\OneDrive\Desktop\project mern stack\webdev-challenge\node_modules\mongodb\lib\cmap\message_stream.js:33:9)
at writeOrBuffer (internal/streams/writable.js:358:12)
at MessageStream.Writable.write (internal/streams/writable.js:303:10)
at Socket.ondata (internal/streams/readable.js:731:22)
at Socket.emit (events.js:400:28)
at addChunk (internal/streams/readable.js:293:12)
Related
I am trying to update few records in table in database but I got FOREIGN KEY constraint failed every time I try. Connection works fine because I tried to post new records and it worked without problems.
This is my backend code:
module.exports = function (server, db) {
// function to insert object to db
function insertTickets(ticket) {
const stmt = db.prepare(
"UPDATE tickets SET userid=?, concertid=?, booked=? WHERE ticketid=?"
);
stmt.run(ticket.ticketid, ticket.userid, ticket.concertid, ticket.booked);
console.log(stmt);
}
server.put("/data/tickets", (request, response) => {
const tickets = request.body;
console.log(request.body);
try {
tickets.forEach((ticket) => {
insertTickets(ticket);
});
response.send("tickets inserted to database");
} catch (e) {
console.error(e);
}
});
};
Data I am trying to update is an array with objects:
const tickets = [
{ticketid: 1, userid: 1, concertid: 1, booked: 1},
{ticketid: 3, userid: 1, concertid: 1, booked: 1}]
Interesting part is, first record is updated only when i try to update two.
UPDATE:
problem solved. I deleted concertid=? and concert parameter.
discord js v13.3.1
I have a set up with my bot that allows me to update and push slash commands via a command, deploy. The deploy command looks like this:
module.exports = {
name: "deploy",
description: "deploys slash commands",
disabled: false,
async execute(interaction, args, client) {
if (interaction.author.id !== process.env.OWNERID) return interaction.reply('You must be the owner to use this!');
const cmds = client.commands
.filter(command => command.slash)
.map(command => {
let {
name,
description = "missing description",
options = [],
slash = false,
defaultPermission = true,
slashPermissions = [],
} = command;
if (typeof name === "string") name = [name];
const cmd = { name: name[0], description, options, defaultPermission, permissions: slashPermissions };
return cmd;
});
await setCommands(interaction.guild?.commands)
.then(interaction.reply(`Registered ${cmds.length} commands to this guild!`));
async function setCommands(commandManager) {
const appCommands = await commandManager.set(
commandManager?.guild ? cmds : cmds.filter(cmd => !cmd.permissions.length)
);
if (commandManager?.guild) {
const fullPermissions = appCommands
.map(appCommand => {
const permissions = cmds.find(cmd => cmd.name === appCommand.name).permissions;
return { id: appCommand.id, permissions };
})
.filter(appCommand => appCommand.permissions.length);
await commandManager.permissions.set({ fullPermissions });
}
}
}
}
I stopped work on my bot awhile back, and now am trying to update the rest of my commands to have slash functionality. I have slash commands registered to my guild, so this command has worked in the past as is. Now, when I try to deploy my slash commands, I am getting this error in my console:
main\node_modules\discord.js\src\managers\ApplicationCommandManager.js:246
options: command.options?.map(o => ApplicationCommand.transformOption(o)),
^
TypeError: command.options?.map is not a function
at Function.transformCommand (main\node_modules\discord.js\src\managers\ApplicationCommandManager.js:246:33)
at main\node_modules\discord.js\src\managers\ApplicationCommandManager.js:163:48
at Array.map (<anonymous>)
at GuildApplicationCommandManager.set (main\node_modules\discord.js\src\managers\ApplicationCommandManager.js:163:22)
at setCommands (main\commands\admin\deploy.js:34:54)
at Object.execute (main\commands\admin\deploy.js:29:19)
at module.exports (main\events\guild\messageCreate.js:28:51)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
For reference, my commands are built as such:
module.exports = {
name: "move",
description: "Move all users from one vc to another",
usage: `\`${process.env.PREFIX}move <vc1> <vc2>\``,
alias: ["mv"],
disabled: false,
slash: true,
options: [
{
name: 'target',
type: 'CHANNEL',
channelTypes: ['GUILD_VOICE'],
description: 'Channel to move users from',
required: true
},
{
name: 'destination',
type: 'CHANNEL',
channelTypes: ['GUILD_VOICE'],
description: 'Channel to move users into',
required: true
}
],
permission: ['MOVE_MEMBERS'],
async execute(interaction, args){
}
}
Is this an issue with how I am building my options blocks in my commands themselves, or how I am parsing them to send to guildCommandManager? I'm assuming the former because the error is a TypeError, but I am historically bad at working with maps and objects, so I could be wrong, and it's hard for me to figure out since the error is being thrown from the djs module and not my code itself
Just use the rest method which you can view the code of it here on the discord.js guide.
https://discordjs.guide/creating-your-bot/creating-commands.html#command-deployment-script
You can create global commands with: applicationCommands
and create local commands for 1 server with: applicationGuildCommands
In attempt to create slash commands in Discord.JS V14 following the official guide, I came across the following error:
DiscordAPIError[50035]: Invalid Form Body
0[LIST_TYPE_CONVERT]: Only iterables may be used in a ListType
The specific command (ping) that I would like to create doesn't have any additional options as it's a very basic command and simply is just unethical to add any options.
ping.js:
module.exports = {
name: "ping",
description: "View the reaction times",
slashInfo: {
enabled: true,
public: false,
},
getSlashInfo: function() {
const { SlashCommandBuilder } = require("discord.js");
const builder = new SlashCommandBuilder();
// Set basic command information
builder.setName(this.name);
builder.setDescription(this.description);
// If the command can be used in DMs
builder.setDMPermission(true);
// Return the information in JSON format
return builder.toJSON();
},
async execute(interaction, _prefix, client) {
interaction.reply({ content: `**Pong** in ${client.ws.ping}ms` });
}
}
commandHandler.js:
function postSlashCommand(data, to, client) {
if (!to) {
// Post command to all guilds
rest.put(
Routes.applicationCommands(client.user.id),
{ body: data }
);
} else {
// Post command for use only in a specific server
rest.put(
Routes.applicationGuildCommands(client.user.id, to),
{ body: data }
);
}
}
async function setupSlashCommands(directory, client) {
// Loop through known command files
const commandFolders = fs.readdirSync(`./${directory}`).filter(file => !file.endsWith(".js") && !file.endsWith(".json"));
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(`./${directory}/${folder}`).filter(file => file.endsWith(".js"));
for (const file of commandFiles) {
// Find the command object
const command = require(`../../${directory}/${folder}/${file}`);
// Ensure the command supports slash
if (!command.slashInfo?.enabled) return;
// Get the slash data
let data = command.getSlashInfo();
// Post the command to Discord
if (command.slashInfo.public) { // If the slash command is public
// Post command to all guilds
postSlashCommand(data, null, client);
} else { // If the slash command is in testing
// Post command for use only in the dev server
postSlashCommand(data, require("../../utils/config.json").DevServer, client);
}
}
}
}
module.exports = (client) => setupSlashCommands("commands", client);
Full error:
throw new DiscordAPIError.DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
^
DiscordAPIError[50035]: Invalid Form Body
0[LIST_TYPE_CONVERT]: Only iterables may be used in a ListType
at SequentialHandler.runRequest (D:\Projects\...\node_modules\#discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:287:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (D:\Projects\...\node_modules\#discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:99:14)
at async REST.request (D:\Projects\...\node_modules\#discordjs\rest\dist\lib\REST.cjs:52:22) {
rawError: {
code: 50035,
errors: {
_errors: [
{
code: 'LIST_TYPE_CONVERT',
message: 'Only iterables may be used in a ListType'
}
]
},
message: 'Invalid Form Body'
},
code: 50035,
status: 400,
method: 'PUT',
url: 'https://discord.com/api/v10/applications/<application_id>/guilds/<guild_id>/commands',
requestBody: {
files: undefined,
json: {
options: [],
name: 'ping',
name_localizations: undefined,
description: 'View the reaction times',
description_localizations: undefined,
default_permission: undefined,
default_member_permissions: undefined,
dm_permission: true
}
}
}
Is there any way to simply create a slash command without providing the options property?
That endpoint takes an array of application commands. Instead of attempting to put a single command at a time, put all of them at once. Add the data to an array, then you will register them
const globalCommands = [],
guildCommands = [];
// Loop through known command files
const commandFolders = fs.readdirSync(`./${directory}`).filter(file => !file.endsWith(".js") && !file.endsWith(".json"));
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(`./${directory}/${folder}`).filter(file => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`../../${directory}/${folder}/${file}`);
// Ensure the command supports slash
if (!command.slashInfo?.enabled) return;
// Add the slash data to the array
if (command.slashInfo.public) globalCommands.push(command.getSlashInfo());
else guildCommands.push(command.getSlashInfo())
}
}
Afterward, simply put the commands, and with what I see, you want to do global and guild commands, separately
postSlashCommand(guildCommands, require("../../utils/config.json").DevServer, client)
postSlashCommand(globalCommands, null, client)
created a nodejs module called role-management, and I published it in azure artifacts(the equivalent of npm repository).
here's the code of this model :
const mongoose = require('mongoose');
exports.getRoles = async (db_url,key) => {
await mongoose.connect(db_url, { useNewUrlParser: true });
const UserSchema= new mongoose.Schema({ },{ strict: false });
const User = mongoose.model('User', UserSchema,'users');
const result = await User.find({ $or: [{ name: key }, { email: key }] });
console.log(result[0].roles)
return result[0].roles
}
I tried to install this module on my project, here's the code which use this module :
const getRoles=required('role-management')
const getItems = async (req, res) => {
try {
const roles = await getRoles(
process.env.db-url,
req.Email
)
res.status(200).json(roles)
} catch (error) {
handleError(res, error)
}
}
module.exports = { getItems }
now the problem is, when I try to hit getItem from an api the first time, it works and i'm getting the roles, but when I try the second time i got this error :
(node:21540) UnhandledPromiseRejectionWarning: RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: undefined
is there something wrong with the role-management module ? mongoose connectivity problem ? could help please ?
I'm super new to databases in general and decided to get started with MongoDB a few days ago. I've run into a problem I cannot find a solution to for the life of me (When I google this issue, people who have these issues are building full blown databases and applications, and the answers are super complicated in return -- I'm just over here trying to update a simple document more than once!)
So, when I run this code, it works PERFECT the first time it is run.
It runs smoothly, logs that the connection was successful, updates the document, returns the string saying it completed successfully, then logs that the disconnect was successful.
But when I run it a second time, I get this error from the debugger console:
(node:37908) [MONGODB DRIVER] Warning: the options [servers] is not supported (Use `node --trace-warnings ...` to show where the warning was created)
warning.js:43(node:37908) [MONGODB DRIVER] Warning: the options [caseTranslate] is not supported
warning.js:43(node:37908) [MONGODB DRIVER] Warning: the options [dbName] is not supported
warning.js:43(node:37908) [MONGODB DRIVER] Warning: the options [srvHost] is not supported
warning.js:43(node:37908) [MONGODB DRIVER] Warning: the options [credentials] is not supported
and this error from the process console:
Connected correctly to server
MongoError: topology was destroyed
at executeCommand (C:\Users\garre\Documents\_Random Projects\Discord Bot\node_modules\mongodb\lib\operations\db_ops.js:222:21)
at FindOneAndUpdateOperation.execute (C:\Users\garre\Documents\_Random Projects\Discord Bot\node_modules\mongodb\lib\operations\find_and_modify.js:118:5)
at C:\Users\garre\Documents\_Random Projects\Discord Bot\node_modules\mongodb\lib\operations\execute_operation.js:72:19
at maybePromise (C:\Users\garre\Documents\_Random Projects\Discord Bot\node_modules\mongodb\lib\utils.js:692:3)
at executeOperation (C:\Users\garre\Documents\_Random Projects\Discord Bot\node_modules\mongodb\lib\operations\execute_operation.js:34:10)
at Collection.<anonymous> (C:\Users\garre\Documents\_Random Projects\Discord Bot\node_modules\mongodb\lib\collection.js:1794:12)
at Collection.deprecated [as findOneAndUpdate] (C:\Users\garre\Documents\_Random Projects\Discord Bot\node_modules\mongodb\lib\utils.js:611:15)
at run (C:\Users\garre\Documents\_Random Projects\Discord Bot\commands\databases\collectinfo.js:50:29)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
Connection Closed
Here's the code that gets run every time I type -collectinfo in my channel (this is on a discord.js bot by the way).
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb+srv://private:private#private.wuiqr.mongodb.net/private?retryWrites=true&w=majority';
const mongo = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });
module.exports = {
name: "collectinfo",
description: "run the code below",
cooldown: 1,
execute(message) {
let id = message.member.id;
let name = message.member.user.username;
async function run() {
try {
await mongo.connect();
console.log('Connected correctly to server');
let col = mongo.db('testDatabase').collection('timeTracking');
// Find doc and update it, if it doesn't exist, create one (i think?)
const myDoc = await col.findOneAndUpdate(
{
"_id": `${id}`
},
{
"$set": {
"_id": `${id}`,
"username": `${name}`,
"messages_sent": 1
}},
{
"upsert": true
}
);
}
catch (err) {
console.log(err.stack);
}
finally {
await mongo.close();
await console.log("Connection Closed")
}
}
run().catch(console.dir);
},
};
So as you can see, everytime the command is run, everything in execute(message){} runs. The first time I run it, it goes just fine and works. The second time I run it, and every time after that -- fail.
I finally found a solution to my issue.
I put all the require/const statements that were outside of the module function INSIDE of the execute() function.
module.exports = {
name: "collectinfo",
description: "run the code below",
cooldown: 1,
execute(message) {
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb+srv://Desura72:golfer72#discordbotcluster.wuiqr.mongodb.net/testDatabase?retryWrites=true&w=majority';
const mongo = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });
let id = message.member.id;
let name = message.member.user.username;
async function run() {
try {
await mongo.connect();
console.log('Connected correctly to server');
let col = mongo.db('testDatabase').collection('timeTracking');
// Find doc and update it, if it doesn't exist, create one (i think?)
const myDoc = await col.findOneAndUpdate(
{
"_id": `${id}`
},
{
"$set": {
"_id": `${id}`,
"username": `${name}`,
"messages_sent": 1
}},
{
"upsert": true
}
);
}
catch (err) {
console.log(err.stack);
}
finally {
await mongo.close();
await console.log("Connection Closed")
}
}
run().catch(console.dir);
},
};
Turns out it only held onto these values the first time around for some reason.