What is the best way to retrieve the content from the MongoDB Document in my GET request?

I encountered an issue while attempting to access the Question field within the JSON document body stored in a MongoDB database. Upon executing the GET request, the result displayed as follows:

{
"_readableState": {
    "objectMode": true,
    "highWaterMark": 0,
    "buffer": {
        "head": null,
        "tail": null,
        "length": 0
    },
    "length": 0,
    "pipes": null,
    "pipesCount": 0,
    "flowing": null,
    "ended": false,
    "endEmitted": false,
    "reading": false,
    "sync": true,
    "needReadable": false,
    "emittedReadable": false,
    "readableListening": false,
    "resumeScheduled": false,
    "destroyed": false,
    "defaultEncoding": "utf8",
    "awaitDrain": 0,
    "readingMore": false,
    "decoder": null,
    "encoding": null
},
"readable": true,
"domain": null,
"_events": {},
"_eventsCount": 0,
"_opts": {},
"_destroyed": false
}

Despite researching about JSON body parsers, integrating them did not resolve my issue. Provided below is my index.js code snippet:

 var express = require('express')
 var mongojs = require('mongojs')
 var bodyParser = require("body-parser");
 var app = express()
 var db = require('./myDB.js')

 app.use(bodyParser.urlencoded({ extended: false }));
 app.use(bodyParser.json());

 app.use(express.json())
 app.listen(4000, () => console.log('Hello'))

 app.get('/getFlashCard', (req, res) => {
 let flashID = req.body._id;
 db.getFlashCard("Interview Questions", flashID, function(docs) {
    console.log("Flashcard retrieved: ", docs);
        res.send(docs);
    });
 });

Below is the content of my myDB.js:

getFlashCard : function(colName, flashID, callback) {
    let data = mongodb.collection("Interview Questions").find({
        "_id" : flashID
    });
    callback(data);
}

Answer №1

Instead of returning the resolved data, you are returning the promise model in this function.

fetchFlashCard : async function(collectionName, cardID, responseHandler) {
 const flashcardData = await mongodb.collection("Interview Questions").find({_id : cardID });

   responseHandler(flashcardData);
}

Answer №2

It's important to note that you should not be waiting for the completion of the find function; instead, you are setting the result of mongodb.collection("").find to data.

To properly wait for the completion of the find function, you can either utilize a callback (refer to https://mongodb.github.io/node-mongodb-native/api-generated/collection.html#find) or use async/await in your code.

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

[Web Development]:

Having an issue with my HTML file where a JavaScript function named "CheckCaptcha" is not being executed when an image is clicked. I've been working on the code for hours, trying different tweaks and modifications, but it still can't seem to find ...

Managing data in MongoDB using upserting and subdocuments

Consider the schema provided below: { '_id' : 'star_wars', 'count' : 1234, 'spellings' : [ { spelling: 'Star wars', total: 10}, { spelling: 'Star Wars', total : 15}, { spelli ...

What is the best way to transfer an element and all its children to another div without losing any jQuery functionality?

At first, sharing an example of the JavaScript and HTML from my page is challenging because I couldn't make it work on JSfiddle. The issue I'm facing involves jQuery on a page where I've created two tabs. Essentially, it's the same con ...

Save the session ID in localStorage instead of a cookie

After successfully logging into my PhoneGap app, everything functions properly. I can send requests within the current session and am authenticated. However, if I completely close the app and reopen it, my session is lost. The cookie containing connect.sid ...

Control the data options available in the autosuggest textbox

I have implemented an autosuggest feature in a text box with predefined values. When typing the first letter in the textbox, a dropdown displays all related values. Is there a way to limit the number of displayed related values to 20? This is what my cu ...

Error Message: Execution Not Recognized and Missing Requirement

After going through numerous threads, I couldn't find a solution to my specific issue. It's quite unclear what I've installed or uninstalled, but I'm hoping that this error message and its details might provide some clarity. Even though ...

What is the best way to obtain an array of downloadable links from Firebase Storage and then store it in an object to be saved in a MongoDB

I have a question regarding setting an array of image links to my createAd function in order to store the result into MongoDB database. Despite getting the image links through the getLinks function as seen below, I always end up with an empty [] array for ...

Utilizing a drop-down selection menu and a designated container to store chosen preferences

My form includes a select dropdown that displays available options (populated from a PHP database). Users can choose options from the list, which are then added to a box below to show all selected items. However, I am facing a challenge with the multiple s ...

The issue with Pymongo's "aggregate" function arose when attempting to use $convert and $toString, however, the problem does not stem from the version of

Overview I am faced with the challenge of converting an ObjectId to a string in order to match the format in the models collection. match = {'$match': { ...simplematch}} uidConversion = {'$addFields': { "uid": {"$c ...

Experience choppy scrolling in Internet Explorer

Check out my click and drag scrolling Image Viewer here. While it functions perfectly in Firefox and Chrome, Internet Explorer is giving me some trouble. The movement seems jerky, especially when scrolling diagonally. It's like the scroll is sluggish ...

What is the best way to manage a batch of files in a response from an Ajax POST request?

Currently, I am utilizing the OGRE web client to convert GeoJSON text data into ESRI shapefiles by making a POST request with Ajax. var data = { "type": "FeatureCollection", "features": [{ "type": "Feature", "geometry": { "type": "Point", "coord ...

Ways to update the content within an IFRAME using server-side methods

I've searched through many posts, but I still haven't found a clear solution to my problem. Here's what's going on: I have a page with an IFRAME that is pulling content from a different domain. The style of the frame doesn't match ...

A technique in MongoDB for grouping by a specific field and tallying the instances of each field value within an array

Within each document, our data structure includes an "Object" with various attributes like "Items" and "Payment". In a test set of 1.9 million documents, we have details such as ItemNumber, ItemName, CashierNumber, and CashierName. { "Object": ...

php utilizing javascript to generate encrypted data for a hidden file

Within my MVC application, I have implemented Raty for rating images. Below is the code snippet: <div class="container"> <form method="post" class='form' role='form' action="?section=photo&view=addVote"> <input t ...

Retrieving multiple selected row values using an ASP Repeater

Within my repeater, I have three values bound: a visible "User Name" column, a visible "Business" column, and a hidden field called "UserId". My goal is to implement the following functionality: when a row is clicked, it should highlight in a different c ...

The class .is-invalid transforms into .is-valid when rendered

Currently, I am incorporating bootstrap into my react project. In this case, I have a variable called mobile that needs to undergo validation whenever there is a change in the input field. Below is the code snippet for the component: const EnterMobile = ( ...

Comparing the positions of elements in Selenium WebDriver with PHP

One of the elements on my webpage serves as a button that reveals a drop-down menu. Due to various factors affecting the page layout, there were some alignment issues between the button and the menu until a few bugs were fixed. I am now looking for a way t ...

Sending data from JavaScript to PHP in the same function

Currently, I am encountering an issue related to passing JavaScript variables to PHP within the same function. Here is a snippet of my code: else if(msg_type[i] == 'code' ){ var code_action = 'test'; <?php function foob ...

What is the process for assigning a function and its arguments as a callback in programming?

Here is a code snippet for your consideration: $scope.delete=function(){ foo('x',3); }; How can we improve the clarity of this code snippet when the callback function contains only one line that calls another function? It's important ...

Switching between two states of a single 'td' element within a column

I am trying to implement a feature where only specific elements in the fourth column of a four-column table toggle when clicked. For example, clicking on an element in the fifth row third column should toggle the corresponding element in the fifth row four ...