Incorporating MongoDB collection elements into a Discord embed display

I am trying to include my collection of documents in an embed using MongoDB's ForEach function.

However, I have noticed that when attempting to add a field to the embed within the forEach loop, it appears that the code sends the message first and then adds the fields subsequently. This behavior is causing some fields to be skipped.

     const Discord = require("discord.js");
    const mongoDb = require("mongodb").MongoClient;

    let showEmbed = new Discord.RichEmbed();
    let proccess = 0;

    module.exports.show = (message, page) => {


            mongoDb.connect('mongodb+srv://admin:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="33000203070673415c515c471e4b5a0a59471d5450431d5e5c5d545c57511d5d5647">[email protected]</a>/eco?retryWrites=true', {
                useNewUrlParser: true
            }, function (err, db) {
                if (err) console.log(err);
                let dbo = db.db("eco");
                dbo.collection("items").find({
                    itemPage: page
                }).forEach(function (doc) {
                    console.log(`${doc.itemName} : ${doc.itemPrice} :  ${doc.itemDescription}`)
                    showEmbed.addField(`**${doc.itemName}** | $${doc.itemPrice}`, doc.itemDescription, false);
                })
            });
message.channel.send(showEmbed);
        }

Answer №1

When you refer to the MongoDB documentation, you will discover that the mongoDb.connect method returns a Promise. This signifies that your code will establish a connection to the database in the background while continuing with the execution of the rest of the code. Consequently, it may send the embed before all the fields are added.

To resolve this issue, you can simply move the message.channel.send inside the Promise block like this:

const Discord = require("discord.js");
const mongoDb = require("mongodb").MongoClient;

let showEmbed = new Discord.RichEmbed();
let proccess = 0;

module.exports.show = (message, page) => {
  mongoDb.connect('Your connect URL here', { useNewUrlParser: true }, function (err, db) {
    if (err) console.log(err);
    let dbo = db.db("eco");

    dbo.collection("items").find({
      itemPage: page
    }).forEach(function (doc) {
      console.log(`${doc.itemName} : ${doc.itemPrice} :  ${doc.itemDescription}`)
      showEmbed.addField(`**${doc.itemName}** | $${doc.itemPrice}`, doc.itemDescription, false);
    });

    message.channel.send(showEmbed);
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Concealing the parent element within the DOM if its children have no content

<div> <h1>Birds</h1> <ul> <li ng-if="bird.type === 'bird'" ng-repeat="bird in creatures">{{bird.name}}</li> </ul> </div> I received data from the server and I need to display it i ...

Switched from btao to Buffer, however encountering a TypeError while trying to push to Vercel

I am currently working on an application in Next.js where I need to encode my image to base64. Initially, I used btao and it worked well until I tried deploying to Vercel, which resulted in an error stating that btao was undefined. After researching a solu ...

Attributes of an object are altered upon its return from a Jquery function

After examining the following code snippet: index.html var jsonOut = $.getJSON("graph.json", function (jsonIn) { console.log(jsonIn); return jsonIn; }); console.log(jsonOut); The graph.json file contains a lengthy JSON fo ...

Angular allows for the creation of dynamic and interactive scenes using Canvas and Three.js

I am in the process of developing a collection of web apps within an Angular SPA. Each individual application is encapsulated within an Angular template, and when navigating between them, specific DOM elements are replaced and scripts from controllers are ...

What is the best way to select and retrieve all span elements generated on my HTML webpage using jQuery?

For retrieving all input texts on my HTML page, I use the following code: var inputs = data.context.find(':input'); $('#result').text(JSON.stringify(inputs.serializeArray())); Once executed, I end up with a JSON string containing th ...

Utilize socket communication with node.js to monitor and identify user

I'm attempting to find a method to unsubscribe from a Redis channel when the user navigates to another page within our website. I have attempted to detect a disconnect socket event when the user clicks on a link, but unfortunately, the event is never ...

Having trouble with the Javascript denial of submit functionality?

I'm dealing with an issue in my code where form submission is not being denied even when the input validation function returns false. I can't figure out what's causing this problem. <script> function validateName(x){ // Validati ...

Incorporating a parameter into a <div> only when the parameter holds a value

Being new to web development, I have a rather basic query. If the datainfo prop variable is not empty, I'd like to include a data attribute in the div tag. <div style={{height: props.height - handleHeight()}} data={datainfo ? datainfo : ""}> C ...

Upgrade your yarn version in order to rectify any yarn audit errors

Currently, there doesn't seem to be a yarn audit --fix command available. Thus, I am exploring different approaches to resolve the errors detected in my yarn audit. While executing a yarn upgrade, some of the errors were successfully addressed, but a ...

What is the best way to retrieve files from MongoDB without streaming them using Node.js, Express, MongoDB, and GridFSBucket?

functions for uploading and downloading files The functions I have for uploading and downloading files are as follows. The uploadFiles function works perfectly and accomplishes its task. However, the download function is not working as intended. It loads ...

Is there a way I can link a variable to a URL for an image?

Creating v-chip objects with dynamic variable names and images is causing an issue. The image source string depends on the name provided, but when I bind the name to the source string, the image fails to load. Despite trying solutions from a similar questi ...

What could be preventing the fill color of my SVG from changing when I hover over it?

I am currently utilizing VueJS to design an interactive map showcasing Japan. The SVG I am using is sourced from Wikipedia. My template structure is illustrated below (The crucial classes here are the prefecture and region classes): <div> <svg ...

How can I trigger HierarchicalDataSource.read() when the kendoDropDownList's change event is fired?

Currently, I am utilizing the treeview and HierarchicalDataSource features of KendoUI. Additionally, I have included a kendoDropDownList at the top of the page. Each time a user changes the value of the dropdown list, it triggers the 'change' eve ...

Why are the links in the navgoco slide menu failing to function properly?

I utilized a demo from jQueryRain to create a collapsible menu using jQuery. However, after completion, I discovered that none of the links were functioning properly. Upon visiting the documentation page, I noticed that many users were encountering the sam ...

Use jQuery to assign a value of "true" when a checkbox is

Can you guide me on how to use jQuery to implement a click function that sets the status value to 'true' if a checkbox is checked, and 'false' if it's not checked? If Checkbox 1 is checked, Status 1 should be set to true. Similarl ...

The state is not updating in a timely manner

After clicking submit in the form, I only receive results upon a second press. When debugging, it appears that setState is updating the state only on the second attempt (userId), but I want it to wait until the state is fully updated (so userId will refl ...

Is there a way to potentially utilize window.open() to open a specific section of a webpage?

My HTML page consists of 2 div blocks and 2 links. I want to open the content of the first div in a new window when the first link is clicked, and the content of the second div in another new window when the second link is clicked. You can find the code h ...

When combining CSS grids, nesting them can sometimes cause issues with the height layout

Check out the code on jsFiddle .component-container { width: 800px; height: 200px; background-color: lightyellow; border: 1px solid red; padding: 10px; overflow: hidden; } .component-container .grid-container-1 { display: grid; grid-tem ...

The HTML table fails to refresh after an Ajax request has been made

I am currently utilizing Ajax to delete a row from the Roles table. The functionality allows the user to add and delete roles using a link for each row. While the deletion process works properly and removes the row from the database, the table does not get ...

Tips for retrieving information from an object stored in JSON format

{ username: 'mn_admin', details: [ { appName: 'node', pid: 5336, starttime: '/Date(1509945756467)/', endtime: '/Date(1509945868200)/', ...