0

find the project that's the least expensive AND has the highest number of ratings AND has the highest average rating. is this the correct method to do it?

exports.getBestEconomicalProject = function(number, callback){  
    var result = ProjectModel.find().sort({averageCost: 1}, {ratingCount : -1}, {averageRating : -1}).select({_id: 1}).limit(number).exec(
            function(err, projects) {
                callback(null, projects)
            }
        );  
    return result;
}
3
  • are you storing averageCost and ratingCount and averageRating in your document? Commented Nov 28, 2012 at 16:30
  • yes they are attributes in each docuyment Commented Nov 28, 2012 at 17:28
  • sounds like an impossible problem - the least expensive project may have lowest number of ratings and have nowhere near the highest average rating - how do you reconcile that? Commented Nov 28, 2012 at 20:08

1 Answer 1

2

You need to combine all sort terms into a single object:

exports.getBestEconomicalProject = function(number, callback){  
    var result = ProjectModel.find()
        .sort({averageCost: 1, ratingCount : -1, averageRating : -1})
        .select({_id: 1})
        .limit(number)
        .exec(
            function(err, projects) {
                callback(null, projects)
            }
        );  
    return result;
}

Or use the string format for the sort:

exports.getBestEconomicalProject = function(number, callback){  
    var result = ProjectModel.find()
        .sort('averageCost -ratingCount -averageRating')
        .select({_id: 1})
        .limit(number)
        .exec(
            function(err, projects) {
                callback(null, projects)
            }
        );  
    return result;
}
Sign up to request clarification or add additional context in comments.

2 Comments

is there a difference in performance between the 2, in terms of runtime for instance?
string version of sort worked for me - object version or array version didn't

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.