-1

I'm working on a discord bot and need to check if a user is in my database or not so that I can make a profile for new users. I'm new at using async functions so I've been looking around for examples but can't seem to get it to work how I want.

Using Typescript / DiscordJS / mongoDB

let profileData;
try {
  const makeProfile = async () => {
    profileData = await profileModels.findOne({ userID: message.author.id });
    if (!profileData) {
      setTimeout(async () => {
        await new profileSchema({
          userID: message.author.id,
          serverID: message.guild?.id,
          balance: 0,
          inventory: [],
          bank: 0,
        }).save();
      }, 1000);
    }
  };
} catch (err) {
  console.log(err);
}
popoispoop
  • 19
  • 2

2 Answers2

1
async function makeProfile() {
  try {
    const profileData = await profileModels.findOne({
      userID: message.author.id,
    });

    await new profileSchema({
      userID: message.author.id,
      serverID: message.guild?.id,
      balance: 0,
      inventory: [],
      bank: 0,
    }).save();
  } catch (error) {
    console.log(error);
  }
}
amlxv
  • 1,610
  • 1
  • 11
  • 18
-1
let profileData; // Left this in global scope in case you want to access it outside the function scope
async function makeProfile() {
  try {
    profileData = await profileModels.findOne({ userID: message.author.id });
    if (!profileData) {
      setTimeout(() => {
        await new profileSchema({
          userID: message.author.id,
          serverID: message.guild?.id,
          balance: 0,
          inventory: [],
          bank: 0,
        }).save();
      }, 1000);
    }
  } catch (err) {
    console.log(err); // Would recommend console.error for errors
  }
}

Make sure to await the function when calling it if you care about the timing.


Since this is a discord bot and the function appears to be initialized inside the message_create listener, you might want to consider making a parameter for message and moving this out of the event listener.

RyloRiz
  • 77
  • 2