AngularJS is encountering an issue with undefined property "then" and is unable

I'm encountering an issue when trying to send a mongodb collection from my server to the client. The error message Cannot read property then of undefined is showing up in the server-side controller. It seems like there is an issue with the promise, but I'm unable to figure it out. What changes need to be made in the code to resolve this issue? Please let me know if you require additional code snippets.

The problem arises at ".then(....)" within the below function.

course.controller.js

function getAll(req,res){
    CourseService.getAll()
        .then(function(result){
            if(result){
                res.send(result);
            }else{
                res.sendStatus(404);
            }
        })
        .catch(function(err){
            res.status(400).send(err);
        });
}

The getAll function in CourseService looks like this:

course.service.js

function getAll(){
    console.log('services/course.service  getALL');
    var deferred = Q.defer();

    db.collection('courses').find().toArray(function(err, result) {
        if (err) deferred.reject(err);
        console.log(result);
        deferred.resolve();
        return deferred.promise;
    });   
}

Answer №1

To fix this issue, ensure the return statement is placed outside of the function block:

function retrieveCourses(){
    console.log('services/course.service  retrieveCourses');
    var promise = Q.defer();

    db.collection('courses').find().toArray(function(error, results) {
        if (error) promise.reject(error);
        console.log(results);
        promise.resolve();
    });   

    return promise.promise;
}

Answer №2

Applying the .then function to a promise is not working because the promise object is not being returned from the getAll function. To fix this, make sure to return the deferred.promise object from the getAll function.

Code

function getAll(){
    console.log('services/course.service  getALL');
    var deferred = Q.defer(); //assuming `Q` is `$q` dependency instance

    db.collection('courses').find().toArray(function(err, result) {
        if (err) deferred.reject(err);
        console.log(result);
        deferred.resolve();
    });   
    return deferred.promise; //return promise from here
}

You have already returned the promise, but it's in the wrong place. Make sure to take it out of the .collection function.

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

Unable to locate the React Native variable named "NetworkStatus"

I have been working on implementing a code to test internet connectivity using react native NetInfo from '@react-native-community/netinfo'. Unfortunately, I keep running into an error that says "Can't find variable: connectionStatus&quo ...

"Using AngularJS $http to iterate through each object in a loop and encounter a problem

I am currently developing an AngularJS app for personal training, but I have encountered a few errors along the way. The issue arises when I receive Json data from an API and try to display a marker for each object. However, I seem to have made a mistake ...

Issue loading ASP.NET MVC in IE7

Encountering an issue with Internet Explorer 7 while using ASP.NET MVC 3. The result page appears as follows: <button type="button" onclick=" ShowOperation('/Page/Box/ShowOperation/CreateBox', '') ">... The error message (specif ...

Amazon Banner Integration for Angular Version 4

Having some trouble getting an Amazon banner to display inside an angular material 2 card. The div appears empty and the banner is not rendering. Any idea what could be causing this issue? Below is the code snippet showcasing my attempts: <md-card clas ...

Top button on my website fails to function

I followed a tutorial to add a "back-to-top" button, and it works on my JSFiddle but not on my live page. The button shows up in Safari but doesn't scroll up. Any ideas why? // Contact Form $(document).ready(function() { $("#contactfrm").submit(f ...

Unable to retrieve component name using React.Children

While working with react in the nextjs framework, I attempted to create my own dropdown component structured as follows: <Dropdown> <DropdownToggle>Action</DropdownToggle> <DropdownMenu> <DropdownItem>Menu 1</Dr ...

Redux Form: Input remains untouched with `touched: false'

Looking to validate my input fields and dynamically change the CSS based on user interaction. To start, I implemented a required validation method by wrapping all input components with a <Field> tag and passing an array of functions to the validate ...

The icons from MaterializeCSS are not displaying correctly on the navbar within an Angular 7 project

Having an issue implementing MaterializeCSS Icons on the navbar. The arrow-drop_down icon is not displaying correctly, showing only text instead. Oddly enough, the icons render properly on other pages except for the app.component.html file. I attempted to ...

Verifying the credentials entered in a form with the data stored in a MongoDB database in order to grant access to a different page using Node.js and Express

As a beginner working on a project using nodejs, express, and mongo db, my goal is to create a scenario where users do not have to register or sign up. Instead, they are provided with a username and password by the administrator, stored in mongodb. To ac ...

Update the main page content dynamically with PHP after the user has successfully logged in

After creating registration and login pages for my website, I am looking to enhance the user experience by displaying their name and image upon logging in. To achieve this, I need to make some modifications to the main page post-login. Below is the code sn ...

How can we use AJAX to incorporate a "like" feature?

I have nearly completed my website, but there is one final obstacle. I would like to add an ajax liking feature. The idea is that when a user clicks on the button, an ajax call should be triggered to increase the value in the database and update it on the ...

React: The rendering is being blocked by costly computation in useEffect

Whenever a user changes the select option, there is some time-consuming work that needs to be done. I want to display a loading message while this work is being carried out, but unfortunately, it's not functioning as expected. import React, { useState ...

Having trouble sending the request body via next-http-proxy-middleware

Recently, I've been attempting to develop a frontend using nextjs that communicates with a Java backend. To achieve this, I'm utilizing the npm package next-http-proxy-middleware. However, it seems like either my request body is getting lost in t ...

Uploading standard image when selecting a file

I have been searching and struggling to find a solution on how to automatically attach a default image when the user clicks "Choose File" using JavaScript or jQuery. My intention is that if the user forgets to attach an image, a default image URL will be ...

A guide on verifying a phone number using just one character

I am looking to validate a phone number with only one character being allowed. For example, the format should be XXX-XXXXXXX where "-" is the only allowed character. Below is my validation function: function validatePhoneNumber() { if(addform.staff_m ...

ADVENTURE BLOCKED - Intercept error: net::ERR_BLOCKED_BY_CLIENT

I've encountered an issue where my initialize function doesn't run properly when a user has an ad blocker enabled. It seems that the ads-script.js file is being blocked by the client with a net::ERR_BLOCKED_BY_CLIENT error, leading to my .done ca ...

Is there a way to refresh the screen and remove the previously drawn object?

I am currently working on implementing the boids algorithm with three.js, and I've hit a roadblock when it comes to drawing the birds (or cubes in my case). The issue I'm facing is that the screen is not clearing after redrawing, so the old cube ...

Determine your age by manually inputting your date of birth

Utilizing Ajax Calendar, I have successfully implemented a feature to calculate age based on the date selected in one textbox and display it in another. However, I am facing two challenges. First Issue:- I want the Age Textbox to be disabled so users cann ...

Error 404 encountered when attempting to send a JSON object to the server

I've been facing a problem while trying to send a JSON object to the server using AJAX calls. I keep getting a 404 Bad Request error. The issue seems to be related to the fact that I have a form where I convert the form data into a JSON object, but th ...

Is there a way to initiate an AJAX post request with the Authorization header for the initial request using Windows Authentication?

I'm working on a web application that has a video page and a Web API for logging purposes. The events are triggered using an ajax post request: function logAction(actionToLog) { $.ajax({ type: 'POST', url: "/api/v/" + cu ...