David Faizulaev
David Faizulaev

Reputation: 5761

Nodejs - Cannot read property then of undefined

I'm getting this error when executing the following code:

getAggregatedRatings(query).then(ratings=>{
    if(ratings){
        return res.json(ratings);
    }else{
        return res.send(200);
    }        
}).catch((error)=>{
    return res.send(500); 
});

function getAggregatedRatings(query){
    movieRating.aggregate(query)
    .exec((err, ratings)=> {
        if (err || !ratings) {
            return Promise.reject(err);
        }
        else {
            return Promise.resolve(ratings);
        }
    });
}

Please note that 'getAggregatedRatings' returns the query results as expected. Please advise what I'm doing wrong.

Upvotes: 1

Views: 1769

Answers (2)

jfriend00
jfriend00

Reputation: 708056

It appears you may be using mongoose for this query. If you're using a recent version of mongoose, then .exec() already returns a promise so you can avoid the promise anti-pattern of wrapping one promise in a manually created new promise whereas you can instead just use the promise it already returns:

function getAggregatedRatings(query){
    return movieRating.aggregate(query).exec().then(result => {
        if (!result) {
            throw new Error("no results found");
        }
    });
}

Upvotes: 0

Pat Needham
Pat Needham

Reputation: 5638

Your getAggregatedRatings function is not returning a promise, or anything for that matter, which explains why when trying to access it, the result is undefined.

Try changing it to this:

function getAggregatedRatings(query){
    return new Promise((resolve, reject) => {
        movieRating.aggregate(query)
        .exec((err, ratings)=> {
            if (err || !ratings) {
                reject(err);
            }
            else {
                resolve(ratings);
            }
        });
    })
}

Upvotes: 3

Related Questions