ThatsLiamS
ThatsLiamS

Reputation: 5

Check if a document in firebase exists

I'm coding a discord.js bot and I want to use firestore as the database

client.on('message', async message => {
    if (message.author.bot || message.guild === null) return;
    let guildInfo = firestore.doc(`servers/${message.guild.id}`)
    if (!guildInfo.exist) {
        guildInfo.set({
            prefix: "!",
            logsOn: false,
            logsID: 0,
            welcomeOn: false,
            welcomeID: 0,
            welcomeMessage: "",
            wordFilterOn: false
        })
    }

This is the start of my message event, and I want it to check if the document exists and if it doesn't to set the variables as shown above. The issue is that this code seems to run for every message and will overwrite its self so If I try and change something, the next message it gets reset

Upvotes: 0

Views: 462

Answers (2)

Saigeetha Sundar
Saigeetha Sundar

Reputation: 144

Couple of things to note here:

  1. get and set operations are done on doc, in your case guildInfo (you receive TypeError: guildInfo.set is not a function because you are trying to perform set operation on top of get rather it should be on doc)
  2. exists is performed on the object you got.

The code should be (with the support of async/await)

let guildInfo = firestore.doc(`servers/${message.guild.id}`);
let guildDoc = await guildInfo.get();

if (!guildDoc.exists) {
   guildInfo.set( {} // your message here
   );
}

To have without the support of async/await @frank-van-puffelen solution should work, except you might have to change !guildDoc.exist to !guildDoc.exists.

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 599061

If you read the Firestore documentation on reading a document you'll see that you need to call get() to actually read the document from the database. With that knowledge, the code would become something like this:

let guildInfo = await firestore.doc(`servers/${message.guild.id}`).get()
if (!guildInfo.exist) {
  ...

If your environment doesn't support async/await the equivalent would be:

firestore.doc(`servers/${message.guild.id}`).get().then((guildInfo) => {
  if (!guildInfo.exist) {
    ...

Upvotes: 1

Related Questions