1

I'm trying to return a mongodb collection from my server to the client, but am getting Cannot read property then of undefined on the server-side controller. I get that there is something wrong with the promise but can't seem to solve it. What code changes are needed to fix this? Let me know if more code snippets are needed.

The error occurs on ".then(....)" in the following 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);
        });
}

CourseService calls this function:

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;
    });   
}
0

2 Answers 2

3

You need to move the return statement outside:

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;
}
Sign up to request clarification or add additional context in comments.

Comments

2

As you are trying to apply .then function over a promise, but promise object haven't being returned from the getAll function. Do return deferred.promise object from the getAll function will return the the promise.

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 that already returned promise, but that is not there in correct place, take it out of .collection function.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.