The array returned by my MongoDB is empty, containing only [] brackets

I'm currently learning how to build full stack JavaScript applications using the MEAN stack, which includes Node.js, AngularJS, Express and MongoDB.

At this stage of my studies, I am tasked with fetching all the hotel data from my database.

However, when I enter http: // localhost: 3000 / api / hotels / in my browser, the database returns an empty array even though the hotel.data.json file is populated.

I attempted to replicate a section5 teacher's final project code, but unfortunately encountered the same issue - my database remains empty [].

This is the snippet from the hotels.controllers file:

var mongoose = require('mongoose');
var Hotel = mongoose.model('Hotel');


module.exports.hotelsGetAll = function(req, res) {


  console.log('GET the hotels');
  console.log(req.query);

  var offset = 0;
  var count = 5;

  if (req.query && req.query.offset) {
    offset = parseInt(req.query.offset, 10);
  }

  if (req.query && req.query.count) {
    count = parseInt(req.query.count, 10);
  }

  Hotel
    .find()
    .skip(offset)
    .limit(count)
    .exec(function(err, hotels) {
      console.log("Found hotels", hotels.length);
      res
        .json(hotels);
    });

};

module.exports.hotelsGetOne = function(req, res) {
  var id = req.params.hotelId;
  console.log('GET hotelId', id);

  Hotel
    .findById(id)
    .exec(function(err, doc) {
      res
        .status(200)
        .json(doc);
    });

};

module.exports.hotelsAddOne = function(req, res) {
  console.log("POST new hotel");
  var db = dbconn.get();
  var collection = db.collection('hotels');
  var newHotel;

  if (req.body && req.body.name && req.body.stars) {
    newHotel = req.body;
    newHotel.stars = parseInt(req.body.stars, 10);
    collection.insertOne(newHotel, function(err, response) {
      console.log("Hotel added", response);
      console.log("Hotel added", response.ops);
      res
        .status(201)
        .json(response.ops);
    });
    
  } else {
    console.log("Data missing from body");
    res
      .status(400)
      .json({
        message: "Required data missing from body"
      });
  }

};

Answer №1

Thank you for responding.

Below is the list of routes:

var express = require('express');
var router = express.Router();

var ctrlHotels = require('../controllers/hotels.controllers.js');

// Hotel routes
router
  .route('/hotels')
  .get(ctrlHotels.hotelsGetAll);

router
  .route('/hotels/:hotelId')
  .get(ctrlHotels.hotelsGetOne);

router
  .route('/hotels/new')
  .post(ctrlHotels.hotelsAddOne);

module.exports = router;

The output from my console.log() shows:

GET /api/hotels
Requested by: undefined
Fetching hotels
{}
(node:2780) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library ins
null
[]
Found 0 hotels

I have a file named hotel-data.json containing information about all the hotels. In a tutorial video, the instructor accessed the database by running mongod in the command prompt. However, I encountered an error while doing so and had to run mongod --dbpath = data instead.

In my main folder, there is an API subfolder with three additional folders:

1 CONTROLLERS folder containing hotels-controllers.js, 2 DATA folder containing db.js, dbconnection.js, hotel-data.json, hotels.model.js, and 3 ROUTES folder containing index.js.

Answer №2

After successfully importing the hotel data from the hotel-data.json file, everything is working as expected. When I type localhost:3000/api/hotels, all the hotels are displayed.

Appreciate the assistance nonetheless.

Aurora

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

The "maxlength" attribute does not function with the input type "number" in an HTML textbox

The maxlength attribute does not seem to be functioning properly when using type="number" ...

Determine the class name of an element when it is clicked on

For various reasons, I am unable to use $('.class').click or on('click', function..) Therefore, I must utilize the onclick="" event from the html element. Is there a way to determine the class of the element where the onclick event oc ...

The Alertify dialog vanished without being able to confirm

While working on some code, I encountered a specific issue: alertify.dialog("confirm").set( { 'labels': { ok: 'Personal', cancel: 'Share' }, 'message': 'Select target:', ...

The current status of the ajax call is set to 0

I am currently attempting to retrieve information from a remote server on my local machine. The readyState seems to be fine, equal to 4. However, the status is consistently showing as 0 instead of 200. When I click the button, it doesn't return anythi ...

Discovering the onClick event of an element in React using the DOM: A step-by-step guide

I have been tasked with implementing analytics events for almost every onclick event on our site. While I am new to analytics, the suggested approach was to create a standardized data set for each event and trigger the analytics event during the onclick a ...

I find myself facing a roadblock in navigating Servlets and HTML

I'm currently immersed in a project aimed at launching an innovative online food ordering platform. To bring this vision to life, I've harnessed the power of HTML, CSS, and JavaScript for frontend development, Java (Servlets) for backend function ...

Error: Material-UI prop type validation failed. Please specify either children, image, src, or component prop for CardMedia component. This error occurred at

I encountered an issue while trying to utilize the CardMedia component from Material-ui. The error message received was 'Failed prop type: Material-UI: Either children, image, src, or component prop must be specified. at CardMedia'. I attempted v ...

Implementing AngularJS with the use of the "bind(this)"

Lately, I have made the switch to using "this" in the controllers and controllerAs in ngRoute and Directives instead of accessing $scope directly. While I do appreciate the aesthetic appeal of the code, I find myself needing to manually bind "this" to each ...

Adjust Text to Perfectly Fit Button

I am developing a quiz using bootstrap and javascript. One issue I encountered is that the text in the buttons can sometimes be longer than the button itself. This results in the text not fitting properly within the button, making it unreadable on mobile ...

Inquiry regarding the ng-disabled directive in AngularJS

<div ng-app="myApp" ng-controller="myCtrl"> <button type="submit" class="btn btn-primary pull-left" ng- disabled="captchaError">Submit</button> </div> <script> var app = angular.module('myApp', []); app.controller( ...

Adding URIs to a post request using JavaScript

I'm struggling to understand how to include URIs in a POST request, similar to this API request: link to example This is my current request, but it's not functioning properly fetch(endPoint, { method: "POST", headers: { Authorization ...

Uploading photos to Postgres through express/multer

Currently, I am using Postman to send images to a POST route through the Express library. However, when I retrieve the buffer of binary data, I am unable to process it accordingly. Will using body-parser resolve this issue? This is how I am uploading the ...

GWT Validation - Enhance Your Application with a Third Party Library

Is there a reliable JavaScript library available for validating GWT fields such as Email, Text Length, Phone Number, Date & SSN, etc.? I am unable to use the GWT Validation Framework or GWT Errai in my application because I receive responses as JSON r ...

When the Next js page loads, it briefly displays a 0 at the top for a moment before loading the rest

When my nextjs app loads a page, there is a momentary appearance of a 0 in the top left corner. This happens even if I am fetching data from Sanity CMS using getStaticProps and returning content. Interestingly, I have observed that simply returning an empt ...

What steps can we take to create a personalized PDF editor incorporating our unique edit functionalities using Vue.js?

Is it possible to create a PDF editor similar to MS Word using vuejs? How can I implement custom logic in the PDF editor with vuejs? For example, the features should include: Conditional replacement of text Adding tags to text within the PDF Changing the ...

Exploring various syntax options for the mongodb module in Node.js

I have been exploring MongoDB integration in Node.js and have come across two different ways to write the code. The first method I found in books and online blogs is: var Db = require('mongodb').Db, Connection = require('mongodb').Con ...

Search for the text using jQuery and then conceal it

I am attempting to conceal specific text within paragraphs, however, the issue is that the script identifies the entire paragraph and removes it completely. My goal is to only remove the text that has been identified. Check out the demo here <div cla ...

Guide on sending a JavaScript variable to PHP using AJAX

I am currently utilizing the following JavaScript code to obtain data from a td element when a button is clicked within an onclick event. function rfk(element) { var element = element.parentElement.parentElement; var id = parseInt(element.childre ...

Retrieving a subset of an array column in Sequelize: A comprehensive guide

I am currently working with a table that has an array column named tokens When querying this table using npm sequelize, I sometimes encounter an issue where the tokens column contains up to 20k elements, even though I only need 10 elements from it. In st ...

Explore various query strings without the risk of JavaScript overwriting references to previous variables

Seeking to extract data from this specific website, I've developed a javascript function that effectively retrieves the necessary information: const total_planning_applications = 39437 const min_value = 39407 var superArray = [] var i = 1 window.loca ...