Reputation: 85
I'm developing a bot for discord, and I'm using the firebase database. In the code below, I want to check if the value mstatus
is set to "CASADO"
, but if this value does not exist yet, execute another command.
database.ref(`Servidores/${message.guild.id}/Users/${message.author.id}/Casamento`).once('value').then(async function(db) {
if (db.val().mstatus === 'CASADO') {
const embederro = new Discord.MessageEmbed()
.setColor(process.env.COLOR)
.setDescription(`**<a:9999:847961716527595520> **Você já está casado. Use \`${process.env.PREFIX}divorciar\` para poder divorciar.`)
.setTimestamp()
.setFooter(moment(message.createdAt).format('D/MM/YYYY'))
.setAuthor(`Awake Bot`,bot.user.displayAvatarURL())
message.channel.send(embederro)
return;
} else {
console.log('OK');
}
})
The code above returns this error:
TypeError: Cannot read property 'mstatus' of null
Upvotes: 1
Views: 101
Reputation: 23160
You could check if the key
of the location of this DataSnapshot
is null
:
database
.ref(`Servidores/${message.guild.id}/Users/${message.author.id}/Casamento`)
.once('value')
.then(async function (snapshot) {
const key = snapshot.key;
if (key === null)
return console.log(`The value doesn't exist yet`);
const val = snapshot.val();
if (val === null)
return console.log(`The value is null`);
if (val.mstatus === 'CASADO') {
const embederro = new Discord.MessageEmbed()
.setColor(process.env.COLOR)
.setDescription(
`**<a:9999:847961716527595520> **Você já está casado. Use \`${process.env.PREFIX}divorciar\` para poder divorciar.`,
)
.setTimestamp()
.setFooter(moment(message.createdAt).format('D/MM/YYYY'))
.setAuthor(`Awake Bot`, bot.user.displayAvatarURL());
return message.channel.send(embederro);
}
console.log(`The value exists but the mstatus is ${val.mstatus}`);
});
Upvotes: 1