'DJS Cannot read properties of null (reading 'premium')
In my code, before it does anything I have it check if there is data
and if there isnt then make a new mongodb collection but when running the command and there is no collection it returns the error Cannot read properties of null (reading 'premium')
and then it creates the mongodb collection so when i run it the second time it works, how would i make the collection create first then run the command?
Code:
run: async (interaction, client) => {
const data = await guildSchema.findOne({
id: interaction.guild.id
});
if (!data) {
const newData = new guildSchema({
id: interaction.guild.id,
name: interaction.guild.name
})
newData.save();
}
const types = interaction.options.getString('type');
const modules = interaction.options.getString('module');
if (types === 'type_enable') {
if (modules === 'module_all') {
if (!data.premium) {
await guildSchema.findOneAndUpdate({
logChannel: interaction.options.getChannel("channel").id,
welcomeChannel: interaction.options.getChannel("channel").id,
goodbyeChannel: interaction.options.getChannel("channel").id,
})
await guildSchema.findOneAndUpdate(filter, update, {
new: true
})
interaction.reply('test')
}
}
}
}
Solution 1:[1]
If you're assigning the variable and then creating the doc if it doesn't find a document, you will need to fetch from the database again after creating the new document.
if (!data) {
const newData = new guildSchema({
id: interaction.guild.id,
name: interaction.guild.name
})
newData.save();
data = await guildSchema.findOne({
id: interaction.guild.id
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Aleks02 |