I am trying to count the entries in a database (w/ a Schema) while only filtering for a particular user (filter), but it keeps not working.
Here is my code:
WarningSchema.find({ user_id: user.id.toString() }).countDocuments((err, count) => {
client.users.cache.get(user.id).send({
embeds: [
new EmbedBuilder().setTitle('Notice').setColor('#2B2D31').setDescription(`You have received an official warning on behalf of the RCA Moderation Team.`).addFields({ name: 'Moderator', value: `<@${interaction.user.id}>`, inline: true }, { name: 'Warning #', value: `${count}`, inline: true }, { name: 'Content', value: reason, inline: false })
]
})
// ...
})
I have tried using the find method in an independent function and assigning it to a variable:
const count = WarningSchema.find({ user_id: user.id.toString() }).countDocuments().exec();
However, that doesn't work, either.
My current codes just returns:
warning.countDocuments({ user_id: '1096621476859351102' })
(Counting warnings for a Discord bot)
The return value of countDocuments
is a Promise.
Therefore the async
problem seems to be the cause.
Using async/await
(or you can use .then()
) it will look like this:
try {
const count = await WarningSchema.countDocuments({ user_id: user.id.toString() });
client.users.cache.get(user.id).send({
embeds: [
new EmbedBuilder()
.setTitle('Notice')
.setColor('#2B2D31')
.setDescription('You have received an official warning on behalf of the RCA Moderation Team.')
.addFields(
{ name: 'Moderator', value: `<@${interaction.user.id}>`, inline: true },
{ name: 'Warning #', value: `${count}`, inline: true },
{ name: 'Content', value: reason, inline: false }
)
]
});
} catch (err) {
console.error('Error counting documents:', err);
}