Mongoose Only Updating Once? - javascript

So I'm making a setnote command so people can keep track of how much they have donated. However, It will only add it when I add them to the database and not after. I don't know why. So it just isn't updating or sending the message that it's even updated.
const { MessageEmbed } = require('discord.js')
const notesModel = require('../models/notesSchema')
module.exports = {
name: 'setnote',
aliases: ['sn'],
description: 'Add a note to a user.',
async execute(message, args, client, cmd, Discord, notesData) {
const mentionedMember = message.mentions.members.first() || message.guild.members.cache.get(args[0])
if (!args[0]) return message.channel.send('Please mention someone to add note to.')
if (!args[1]) return message.channel.send('Please state an amount to add to the user.')
const amountToAdd = args[1]
if (isNaN(args[1])) return message.channel.send('You have to add a number when setting note.')
let userData = await notesModel.findOne({
userID: mentionedMember.id,
serverID: message.guild.id,
})
if (!userData) {
userData = await notesModel.create({
userID: mentionedMember.id,
serverID: message.guild.id,
notes: 0
})
const response = await notesModel.findOneAndUpdate({
serverID: message.guild.id,
userID: mentionedMember.id
}, {
$inc: {
notes: +amountToAdd
}
})
userData = await notesModel.findOne({serverID: mentionedMember.guild.id, userID: mentionedMember.id});
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
const addedNote = new MessageEmbed()
.setTitle(`<a:red_check:845104782833352704> Successfully Added Note <a:red_check:845104782833352704>`)
.setDescription(`${mentionedMember.user.tag} has now donated \`${numberWithCommas(userData.notes)}\``)
.setColor('GREEN')
message.channel.send(addedNote)
}
}
}

Related

MongoDB only using one entry - Discord.js

Currently I have a command of which checks someone else's balance with my sort of economy system. The issue is that it's only storing one users data - so when the database is empty and the bot goes to create a profile for a user that is the only profile ever created - for example when another member goes to check their balance then it won't show their own profile but it shows only the first person to create a profile's balance. I've tried everything - nothing works. Please help... Below is the command to check balance, my schema and the profile creating function.
if (message.author.bot) return;
let member = message.mentions.members.first();
if (member) {
if (message.content.match('!ponyo balance') && profileSchema.findOne({ memberId: member.id, guildId: member.guild.id })) {
console.log('trying to execute balance.createBalance() with the user id: ' + member.id)
const profileBalance = await balance.createBalance(member);
console.log(`profileBalance: ${profileBalance}`)
await message.reply(`${message.mentions.members.first()} has ${profileBalance.coins} coins! :D`);
}
}
})
const Balance = require('./profileSchema')
const mongoose = require('mongoose')
//create profile thingy
async function createBalance(member) {
if (Balance.findOne({ memberId: member.id })) {
let balanceProfile = await Balance.findOne({ memberId: member.id })
if (balanceProfile) {
return balanceProfile;
} else {
balanceProfile = await new Balance({
userID: member.id,
serverID: member.guild.id
});
await balanceProfile.save().catch(err => console.log(err));
console.log("returning: " + balanceProfile.toString());
return balanceProfile;
}}}
module.exports = { createBalance };
const mongoose = require('mongoose');
const profileSchema = new mongoose.Schema({
userID: { type: String, require: true, unique: true},
serverID: { type: String, require: true },
coins: { type: Number, default: 100 },
bank: { type: Number }
})
const model = mongoose.model('ProfileModels', profileSchema);
module.exports = model;
There is no memberId in your profile Schema..
if (Balance.findOne({ memberId: member.id })) {
Maybe you are mistakenly put memberId instead of userId or
you have Separate Balance Scheme.. which is not imported Correctly..

how to check if the member is joined to an specific voice channel DiscordJS

I want to check if the member is joined to the voice channel that the bot is joined.
The whole code is working, I just want to add that line that I put in code comments.
My code:
const { QueryType } = require('discord-player');
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'play',
aliases: ['p'],
permissions: ['CONNECT'],
description: 'Plays a music',
voiceChannel: true,
async execute(message, args, cmd, client, Discord, profileData) {
// if the member that used the comamnd is not joined to the voicechannel that the bot is playing music on it, return;
const player = client.player
if (!args[0]) return message.channel.send({ content: `${message.author}, Write the name of the music you want to search. <:Cross:961558777667149874>` });
const res = await client.player.search(args.join(' '), {
requestedBy: message.member,
searchEngine: QueryType.AUTO
});
if (!res || !res.tracks.length) return message.channel.send({ content: `${message.author}, No results found! <:Cross:961558777667149874>` });
const queue = await client.player.createQueue(message.guild, {
metadata: message.channel
});
try {
if (!queue.connection) await queue.connect(message.member.voice.channel)
} catch {
await client.player.deleteQueue(message.guild.id);
return message.channel.send({ content: `<:Cross:961558777667149874> ${message.author}, I can't join audio channel ` });
}
if(client.config.opt.selfDeaf === false) {
let channel = message.member.voice.channel;
const { joinVoiceChannel } = require('#discordjs/voice');
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
selfDeaf: false
});
}
res.playlist ? queue.addTracks(res.tracks) : queue.addTrack(res.tracks[0]);
if (!queue.playing) await queue.play();
},
};
I am not getting any errors.
I am using node.js v16 and discord.js v13
You can use this code to return if the member isn't in the same voice channel as you.
if(message.member.voice.channelId !== message.guild.me.voice.channelId) return;
Then it will return if they aren't in the same channel.

TypeError: Cannot read properties of undefined (reading 'createLap') MongoDB, Mongoose, JavaDcript, Discord.JS

I am working on a discord bot. And, I am having issues writing to the database. I am using these three files to communicate with the database. For some reason I am getting a:
TypeError: Cannot read properties of undefined (reading 'createLap') Error. It is coming from the second file that I posted.
const mongoose = require('mongoose');
const lapSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
guildId: String,
memberId: String,
laps:{type: Number, default: 0},
})
module.exports = mongoose.model('Lap', lapSchema, 'laps');
const { SlashCommandBuilder } = require('#discordjs/builders');
const Lap = require('../../schemas/lap');
module.exports = {
data: new SlashCommandBuilder()
.setName('lap')
.setDescription('It\'s been a pleasure watching you race! Let\'s take a look at your stats!')
.addSubcommand(subcommand =>
subcommand
.setName("tag-someone-else")
.setDescription("Gets laps of a user that has been tagged!")
.addUserOption(option => option.setName("target").setDescription("The user mentioned"))),
async execute(interaction, client) {
let user = (interaction.options.getUser("target") ? interaction.options.getUser("target") : interaction.user);
console.log(user);
const userProfile = await client.createLap(interaction.member);
await interaction.reply({content: `${interaction.user.tag} has ${userProfile.laps}.`})
},
};
const mongoose = require("mongoose");
const Lap = require('../schemas/lap');
module.exports = (client) => {
client.createLap = async (member) =>{
console.log("Hitting here");
let lapProfile = await Lap.findOne({memberId: member.id, guildId: member.guild.id});
if (lapProfile){
return lapProfile;
}else{
console.log("hits here")
lapProfile = await new Lap({
_id: mongoose.Types.ObjectId(),
guildId: member.guild.id,
memberId: member.id,
});
await lapProfile.save().catch(err => console.log(err));
console.log("Lap Created! This is great news.");
return lapProfile;
}
};
};
module.exports = (client) => {
client.handleEvents = async (eventFiles, path) =>{
for (const file of eventFiles) {
const event = require(`../events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client));
}
}
}
}

How do I log new bans?

I'm working on something and I need to add ban logging, I tried something but it doesn't send anything.
Any help would be appreciated!
client.on('guildBanAdd', async (guild, user) => {
let Banch = await client.channels.cache.get('ID')
const fetchedLogs = await guild.fetchAuditLogs({
limit: 1,
type: 'MEMBER_BAN_ADD',
});
const banLog = fetchedLogs.entries.first();
if (!banLog) return console.log(`${user.tag} was banned from ${guild.name} but no audit log could be found.`);
const embed = new Discord.MessageEmbed()
.setTitle(`Member Banned`)
.setDescription(`${guild.name}`)
.setColor("RED")
.addField(`Member`, `\n${username}`)
Banch.send(embed)
}
);
This should work
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('guildBanAdd', async (guild, user) => {
const banned = await guild.fetchAuditLogs({
type: 'MEMBER_BAN_ADD',
limit: 1
});
const channel = client.channels.cache.get('ID');
if(!channel) return console.log(`Channel was not found!`);
const userbanned = banned.entries.first();
const { executor, target } = userbanned; // get the user who banned the user and the user that got banned
if(target.id !== user.id) return console.log(`Invalid data in the audit logs!`); // check if the user that got banned in the Audit Logs is the user that is banned
const embed = new Discord.MessageEmbed()
.setTitle(`Member Banned`)
.setDescription(`${guild.name}`)
.setColor("RED")
.addField(`Member`, `${target.username}`);
channel.send(embed).catch(err => {
console.log(err);
});
});

findOneAndUpdate is not a function of mongoose

I know this question has been answered before but I can't seem to implement the changes into what im working with. I'm trying to create a daily command that rewards a user for doing s!daily. I get the error,
TypeError: profileData.findOneAndUpdate is not a function
at Object.execute (C:\Users--\Desktop\DiscBot\commands\daily.js:35:43)
at module.exports (C:\Users--\Desktop\DiscBot\events\client\message.js:34:13)
daily.js, one having error at line 35 for findOneAndUpdate is not a function
const Schema = require('../models/profileSchema')
//cache users that claim daily rewards
let claimedCache = []
const clearCache = () => {
claimedCache = []
setTimeout(clearCache, 1000 * 60 * 10)
}
clearCache()
//message to make it easier later
const alreadyClaimed = 'You have already claimed your daily rewards'
module.exports = {
name: "daily",
aliases: ["day", "d"],
permissions: [],
description: "Claim your daily rewards!",
async execute(message, args, cmd, client, Discord, profileData) {
const { serverID, member } = message
const { id } = member
//If user is in cache return message
if (claimedCache.includes(id)) {
console.log('Returning from cache')
message.reply(alreadyClaimed)
return
}
//Put everything in object for later
const obj = {
guildId: serverID,
userId: id,
}
//Results is an update that either updates if is user is not in array and doesn't if they are, but it doesn't know what findOneAndUpdate is (thought it was just a mongo/mongoose function??)
try {
const results = await profileData.findOneAndUpdate(obj)
console.log('RESULTS:', results)
if (results) {
const then = new Date(results.updatedAt).getTime()
const now = new Date().getTime()
const diffTime = Math.abs(now - then)
const diffDays = Math.round(diffTime / (1000 * 60 * 60 * 24))
if (diffDays <= 1) {
claimedCache.push(id)
message.reply(alreadyClaimed)
return
}
}
//after the update increase coins by 50 and send claimed message
await profileRewardsSchema.findOneAndUpdate(obj, obj, {
upsert: true,
})
claimedCache.push(id)
const amount = 50;
await profileModel.findOneAndUpdate(
{
userID: id,
},
{
$inc: {
coins: amount,
},
}
);
message.reply('You have claimed your daily rewards!')
}catch (err) {
console.log(err);
}
}
}
message.js, heres where I make profileModel a thing using mongoose to pass it into my commands
const profileModel = require("../../models/profileSchema");
const config = require('../../config.json');
module.exports = async (Discord, client, message) => {
//command handler start
const prefix = 's!';
if (!message.content.startsWith(prefix) || message.author.bot) return;
//database junk
let profileData;
try {
profileData = await profileModel.findOne({ userID: message.author.id });
if (!profileData) {
let profile = await profileModel.create({
userID: message.author.id,
serverID: message.guild.id,
coins: 10,
bank: 0,
});
profile.save();
}
} catch (err) {
console.log("Error creating new database profile");
}
const args = message.content.slice(prefix.length).split(/ +/);
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd) || client.commands.find(a => a.aliases && a.aliases.includes(cmd));
if(!command) return message.channel.send(":x: This is not a valid command");
try {
command.execute(message, args, cmd, client, Discord, profileData);
} catch (err) {
message.reply('There was an error executing that command!');
}
};
profileSchema.js, Where profile is made into mongo database
const mongoose = require("mongoose");
const profileSchema = new mongoose.Schema({
userID: { type: String, require: true, unique: true },
serverID: { type: String, require: true },
coins: { type: Number, default: 10 },
bank: { type: Number },
},
{
timestamps: true,
}
)
const model = mongoose.model("ProfileModels", profileSchema);
module.exports = model;
main.js, where mongoose is connected, then passed on
mongoose.connect(process.env.MONGODB_SRV, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
You are trying to call findOneAndUpdate on the document, which you passed to execute function at message.js. Check the example of how to use findOneAndUpdate
https://mongoosejs.com/docs/tutorials/findoneandupdate.html
Most of the time this error happen when you call findOneAndUpdate in mongoose when you call it on the instance of the model NOT the actual model
so instead of this
var NewUser = new User(req.user);
NewUser.findOneAndUpdate...
do this
var NewUser = new User(req.user);
User.findOneAndUpdate(
{ name: NewUser.name },
{ name: NewUser.name},
{ upsert: true });

Categories

Resources