Is there a way to save every username change into some kind of array (using mongodb)

Right now I'm using this Schema to push user info to mongodb
const addUser = async (user) => {
const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
userId: { type: String, required: true, unique: true },
username: { type: String, required: true },
discriminator: { type: String },
isBot: { type: Boolean, default: false },
usernameHistory: { type: [String], default: [] }
});

module.exports = mongoose.model('User', UserSchema);
const addUser = async (user) => {
const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
userId: { type: String, required: true, unique: true },
username: { type: String, required: true },
discriminator: { type: String },
isBot: { type: Boolean, default: false },
usernameHistory: { type: [String], default: [] }
});

module.exports = mongoose.model('User', UserSchema);
and this code to listen to userUpdate
client.on('userUpdate', async (oldUser, newUser) => {
try {
if (oldUser.username !== newUser.username) {
console.log(`User ${oldUser.username} changed name to ${newUser.username}`);

const user = await User.findOne({ userId: newUser.id });

if (user) {
user.username = newUser.username;
if (!user.usernameHistory.includes(oldUser.username)) {
user.usernameHistory.push(oldUser.username);
}

await user.save();
console.log(`Updated username for User ID: ${newUser.id}`);
} else {
console.log('User not found in the database.');
}
}
} catch (error) {
console.error('Error updating user:', error.message);
}
});
client.on('userUpdate', async (oldUser, newUser) => {
try {
if (oldUser.username !== newUser.username) {
console.log(`User ${oldUser.username} changed name to ${newUser.username}`);

const user = await User.findOne({ userId: newUser.id });

if (user) {
user.username = newUser.username;
if (!user.usernameHistory.includes(oldUser.username)) {
user.usernameHistory.push(oldUser.username);
}

await user.save();
console.log(`Updated username for User ID: ${newUser.id}`);
} else {
console.log('User not found in the database.');
}
}
} catch (error) {
console.error('Error updating user:', error.message);
}
});
4 Replies
d.js toolkit
d.js toolkit3mo ago
- What's your exact discord.js npm list discord.js and node node -v version? - Not a discord.js issue? Check out #other-js-ts. - Consider reading #how-to-get-help to improve your question! - Explain what exactly your issue is. - Post the full error stack trace, not just the top part! - Show your code! - Issue solved? Press the button!
Sqqs
SqqsOP3mo ago
This doesn`t work btw
Unknown User
Unknown User3mo ago
Message Not Public
Sign In & Join Server To View
Mark
Mark3mo ago
Should keep in mind that this is considered end user data and has special considerations for storing it according to the dev TOS

Did you find this page helpful?