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

Utilize VueJS to bind a flat array to a v-model through the selection of multiple checkboxes

My Vue component includes checkboxes that have an array of items as their value: <div v-for="group in groups"> <input type="checkbox" v-model="selected" :value="group"> <template v-for="item in group"> <input type ...

Retrieving embedded documents from Mongoose collections

I am currently facing challenges in caching friends from social media in the user's document. Initially, I attempted to clear out the existing friends cache and replace it with fresh data fetched from the social media platform. However, I encountered ...

Having trouble getting async and await to function properly

Why is my code not waiting for validation and running the else part immediately? Can you help me find the mistake? async validateBeforeSubmit(event) { await this.$validator.validateAll().then(result => { if (result) { ...

Converting text data into JSON format using JavaScript

When working with my application, I am loading text data from a text file: The contents of this txt file are as follows: console.log(myData): ### Comment 1 ## Comment two dataone=1 datatwo=2 ## Comment N dataThree=3 I am looking to convert this data to ...

Best method for linking asynchronous requests using axios

Is it possible to make an API call using axios based on the response of another initial API call, all within asynchronous functions? I attempted the following approach with await/promise: function fetchUserDetails(userId) { return axios.get( "https://a ...

The mouse movement event will not be triggered for every frame when a keyboard event occurs

When the mouse is moving in a browser, ideally the mousemove event should fire every frame. However, if a key is pressed or released (or repeated), the mousemove event stops firing for a frame or two. To test this behavior, you can use the code snippet bel ...

Organizing a Vue.js SPA project: Implementing Vuex store and API calls efficiently

Here is how I have organized the structure of my Vue app: components/ article/ AppList.vue common/ AppObserver.vue NoSSR.vue layout/ AppFooter.vue AppHeader.vue ui/ AppButton. ...

Vue is removing a DOM node during the created lifecycle hook to set up a component

I am currently working on understanding the issue with this example that is not behaving as expected. My goal is to initialize my ContentView using the server-side rendered HTML in the DOM. I plan to check if init__main-content exists and then initialize t ...

transferring a document using axios, bypassing the FormData interface

One way to upload a file to the server is by using axios along with the FormData api. Here's an example: persist(photo){ let data = new FormData(); data.append('photo', photo); axios.post(`/api/photos/${this.user ...

Encountering a strange issue when attempting to link app.js with mongodb

I recently set up MongoDB and the Compass, everything was working fine until I tried to connect MongoDB with my app.js. Now I'm getting a strange error message. Could anyone help me understand what this error means and how I can fix it? Unfortunately, ...

AngularJSError

I am completely new to AngularJS and I've been tasked with debugging someone else's code. While debugging in Google Chrome, I encountered the following error: TypeError: accountService.logIn(...).success is not a function. The issue lies with ...

Is it possible for AngularJS to share a service among multiple ng-apps?

I've been working on developing a web app that involves multiple Angular ng-apps, and I want to use the same service code for at least two of them (even though they don't share data but perform similar functions). How can I prevent code duplicati ...

Add the AJAX response to the dropdown menu options

Currently in my project, I am utilizing Laravel as a backend. The scenario is such that once the corresponding page loads, it triggers an ajax request to fetch vehicle data which consists of vehicle model and plate number properties. My aim is to display t ...

Vue.js v-cloak lifecycle method

Currently, I am working on a project where I have styled v-cloak with display: none, and it is decorating the body. As a result, everything remains hidden until the Vue instance is ready. I have created a component that inserts a chart (using highcharts). ...

Executing the outer function from within the inner function of a different outer function

Imagine this scenario: function firstFunction() { console.log("This is the first function") } secondFunction() { thirdFunction() { //call firstFunction inside thirdFunction } } What is the way to invoke firstFunction from thirdFunction? ...

Using jQuery to dynamically insert a table row with JSON data into dropdown menus

I'm working on a web form that includes a table where users can add rows. The first row of the table has dependent dropdowns populated with JSON data from an external file. Check out the code snippet below: // Function to add a new row $(function(){ ...

"Discover the step-by-step process of transforming an input field value into a checkbox with

I've been experimenting with creating a To-Do list using HTML, CSS, and Javascript. I've managed to capture the input field value in a fieldset so far. However, my goal is to find a way to transform the input field value from the textfield into a ...

Display the closest locations on the Google Maps interface

I am currently working on a project that involves integrating Google Maps. The project includes storing hospital addresses (in longitude and latitude) in a database. However, I need assistance in displaying the nearest hospital from my current location. I ...

Ways to send information from Vue instance to nested components

Currently, I am fetching data using AJAX from the Vue instance and trying to pass it onto different components. As I delve deeper into learning Vue.js, I can't help but notice that the documentation seems a bit scattered... This snippet showcases wha ...

Using $stateParams injection for unit testing Angular applications with Karma

Here is the starting point for the controller code: angular .module('hc.hotelContent') .controller('NameLocationController', nameLocationCtrlFn); //Todo change hotelDataService nameLocationCtrlFn.$inject = ['$stateParams', &a ...