Retrieving information from MongoDB

Currently, I am working on retrieving data from MongoDB and passing it to my Express server to eventually display it in my HTML using Angular. The retrieval process is successful when there is only one record in the database. However, if multiple records are created, an error appears in the console:

"can't send headers after they are sent"

This is how my "get" request looks like in Express:

router.get('/getdata', function(req, res, next){
var findDocuments = function(db, callback) {
var cursor = db.collection('userdata').find({});
cursor.each(function(err, doc) {
  assert.equal(err, null);
  if (doc != null) {
     res.status(200).json(doc);
  } else {
     callback();
  }
});
};
  mongo.connect(url, function(err, db) {
   assert.equal(null, err);
  findDocuments(db, function() {
    db.close();
  });
});
  console.log('Items have been returned');
});

Answer №1

router.get('/fetchData', function(req, res, next){

  var retrieveData = function(database, callback) {

    // Set conditions to filter out null or empty documents
    // Replace key with the field of your document
    var cursor = database.collection('userdata').find({'key' : {$exists : true}});

    // Return all documents if available
     if(cursor){
    return callback(cursor);
    }else{
    return callback([]);
       }

  };

  mongo.connect(url, function(err, db) {
   assert.equal(null, err);
   retrieveData(db, function(docs) {
    db.close();

    // Send the retrieved documents here 
    console.log(docs);
    res.status(200).send(docs);

  });
 });

  console.log('Items have been returned');
});

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

sending back a JSON object that appears empty, despite actually containing data

I'm facing an issue where I am attempting to send a json response to my react client, containing a list of songs (objects). However, the json returns as an empty array. This is how I am fetching the data: let songs = []; fetch("https://api.spotify. ...

The JSON data in CRM 2011 is displaying as undefined, but the URL is still showing the

I have been struggling with a simple odata query where the call is successful, but I keep getting undefined results. I've tried various methods to inspect the object, but it still shows undefined. What could be causing this issue? UPDATE: After some ...

Exploring Mongoose: A Guide to Populating Data from a Parent to a Child

I'm currently diving into the world of mongoose, where I have set up 3 collections (User, Post, Comment), each with its own unique schema: User { fullName: String, email: String, } Post { author: {type: mongoose.Schema.Types.ObjectId, required ...

Issues with hot reloading in Express.js - GraphQL API are preventing it from functioning properly

In an attempt to create a mockAPI with hot reload functionality, I encountered an issue. Whenever I edit the schema or the data returned by the server and restart it, the changes are not reflected (I tested this using Postman). I believed that restarting ...

Resetting suggestions for autocompletion in AngularJS

Currently implementing angularJS with autocomplete-alt. The functionality is working smoothly, but I've encountered an issue when clearing the autocomplete input using an AngularJS function - the suggestion list does not update accordingly. How can I ...

Transform a collection of hierarchical strings into JSON using C#

I have a series of strings that represent hierarchical information and are separated by hyphens (3 hyphens indicate separation). My goal is to convert this list into a JSON format so that I can link it to a tree control component. I am in search of a C# s ...

Harness the power of AngularJS by crafting your unique

Hey there! I'm having a bit of trouble figuring out why this isn't showing up. Both View1.html and View2.html are in the partials folder, so that's not the issue. Sometimes the screen is completely blank, other times I only see a Name: label ...

The skin colors are failing to load on JWPlayer7

I've encountered a strange issue with jwplayer. I'm setting it up from an Angular JS Controller and loading it using a simple preview button that loads the jwplayer with the specified configuration. It should be straightforward. jwplayer(id).s ...

Unexpected token error occurs when making cross-domain AJAX requests to the server and receiving a JSON object

I have set up an express server to handle get requests to specific url endpoints. When responding to these requests, I am sending back data in JSON format to enable making Ajax calls and retrieving data from the page. To allow for cross-domain requests, I ...

Having trouble getting my local website to load the CSS stylesheet through Express and Node.js in my browser

https://i.stack.imgur.com/qpsQI.png https://i.stack.imgur.com/l3wAJ.png Here is the app.js screenshot: https://i.stack.imgur.com/l3wAJ.png I have experimented with different combinations of href and express.static(""); addresses. However, I am ...

employing the default value in conjunction with an ejs filter

If item.description is not defined or empty, how can I default to 'No description'? Here are the options I've experimented with: <%-: (item.description | markdown) || '<p>No description</p>' %> <%-: (item.des ...

How to Extract Information from a Table Enclosed in a Div Using HTML Parsing?

I'm new to HTML parsing and scraping, looking for some guidance. I want to specify the URL of a page (http://www.epgpweb.com/guild/us/Caelestrasz/Crimson/) to grab data from. Specifically, I'm interested in extracting the table with class=listing ...

Upon completion of the user registration process, the req.isAuthenticated method is showing a false

I've encountered this issue in a few of my previous apps and I'm unsure what's causing it. When I navigate to the login page and successfully log in a user, everything works as expected and I have access to the logged-in user. However, when ...

transferring data from ejs template

In my app.js file, I have an array that stores files. To display these files on a website, I use a for-loop in ejs: <% for(let i = 0;i<posts.length; i++){ %> <li class="listtitle"> <%= posts[i].title %> </li> ...

Using jQuery Datatables fnReloadAjax successfully triggers a reload of the data, however, it

In my jQuery datatable, I am utilizing the code below to refresh the data: $(".unread-rows").click( function(e) { e.preventDefault(); message_table.fnReloadAjax("/letters/ajax/inbox/1"); message_table.fnDraw(); $(this).addClass("active").s ...

If the div element undergoes a change, use an if-else condition to populate the data fields accordingly

I'm looking to create a basic if/else statement in JavaScript that checks if a div element has changed before populating JSON data fields/variables that pull from dynamically updated HTML. I want to avoid using the deprecated DOMSubtreeModified metho ...

Exploring the Dev Tools Console feature in Excel for Windows

I have developed an Excel add-in using AngularJS. I utilize <div ng-show="isLoggedIn">...</div> and <div ng-show="!isLoggedIn">...</div> to manage different content based on the value of $scope.isLoggedIn. While it functions well i ...

Sharing images on a web app using Express and MongoDB

My objective is to develop a portfolio-style web application that allows administrators to upload images for other users to view. I am considering using Express and MongoDB for this project. I am uncertain about the best approach to accomplish this. Some ...

Combining JSON data within a MySQL column efficiently with the power of SQLAlchemy

Is there a way to consolidate JSON data that is spread out over multiple rows in a MySQL column using the Python SQLAlchemy library? I tried using json_merge_preserve but encountered difficulties applying it to an entire column. This was the code snippet ...

What factors should be considered when deciding whether to create an entity in Django using Tastypie, based on data from another entity?

In my Event class, I have defined the number of participants and the participant limit. Additionally, there is a Ticket class which represents registration for the Event. I need to ensure that tickets for an event are not created if the event has reached ...