Home > Enterprise >  How do I import values ​from MongoDB into a Discord embed?
How do I import values ​from MongoDB into a Discord embed?

Time:05-30

I have all the data I need in the mongoDB Database, I just dont know how I can send parts of the data in an Discord embed. for example the data:

new birthdaySchema({
  User: username.username,
  Birthday: birthdayString, 
  Month: showMonth,
  Day: showDay, 
  Year: showYear

Year, Month and Day are just there to sort the birthdays and birthdayString = Day of Month

I also use moment-timezone (UTC)

const dateTime = moment.utc().format(`DD MM YYYY, hh:mm:ss`);

My goal is with a slash commad like /next-birthdays the data in the embed should look like

${birthdayString} ${Year}\n${User} (and this 10 times, so the the upcoming birthdays of 10 users)

And if the birthday and the actual date and time from moment-timezones (UTC) is matching. Then the Bot should make a new embed with a title (Happy Birthday) and in the description (Today is ${User}'s Birthday, blah blah blah) and at last it should give that User the birthday role on this server.

Hope someone can help me :)

CodePudding user response:

I have something similar to what might be able to help you :) This is achieved by using the mongoose library (which I'm guessing you are likely using).

In my code I have a reference to the JS file where my schema is held:

const Messages = require("../models/benSchema2");

Then, you could have a variable and store all entries from the database inside it in an array form, like this:

const messageOrdered = await Messages.find({}).sort({ messages: -1 });

(In my case, I get all entries from the database, sorting by descending order of messages. Perhaps you might be able to sort it based on birthdayString?)

Then you can have a for loop, starting at i=0 and stopping at 9 which should get the nearest 10 birthdays. I have my code in here but it could be refactored to be more efficient. Also, my code works based off user ID data being stored in the database but it should be able to work by refining it to work on usernames.

let content = "";
    for (let i = 0; i < messageOrdered.length; i  ) {
      if (i === 5) {
        break;
      }

      const userID = await client.users.fetch(messageOrdered[i].UserID);
      let user = userID.username;

      if (i === 0) {
        content  = `           
  • Related