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
and this code to listen to userUpdate
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);
}
});