bouncingHippo
bouncingHippo

Reputation: 6040

mongoose query for top 5 viewed projects (sorted) using nodeJS

i have a site with multiple projects. and each project has a different view count. What i want to do is to retrieve an array of the top 5 viewed projects in this order [max, max-1, max-2, max-3, max-4].

here's the schema:

var mongoose = require('mongoose');

// defines the database schema for this object
var schema = mongoose.Schema({
  projectName : String,
  authorName : String,
  viewCount : Number

   comment : [{
      id : String,                                  
      authorName : String,
      authorEmailAddress : { type : String, index : true }  
    }]
  });

})

// Sets the schema for model
var ProjectModel = mongoose.model('Project', schema);

// Create a project
exports.create = function (projectJSON) {

  var project = new ProjectModel({

    projectName : projectJSON.projectName ,
    authorName : projectJSON.authorName,    
    viewCount :  projectJSON.viewCount,    

    comment : [{
      id : projectJSON.comments.id,                                         
      authorName : projectJSON.comments.authorName,                         
      authorEmailAddress : projectJSON.authorEmailAddress
    });

  project.save(function(err) {
    if (err) {
      console.log(err);
    }
    else{
      console.log("success");
    }
  });


}

Below is my attempt to retrieve an array of the top 5 viewed articles in this order [max, max-1, max-2, max-3, max-4]. Bearing in mind that articles view rank change in real time.

// because i am familiar with SQL, i start with a SQL query and convert it later to mongoose

SQL version:

SELECT MAX(viewCount) FROM project where projectName=1 --this only give the MAX when i want the top 5

mongoose version:

exports.getTopViewedProject = function(rank, callback)
   ProjectModel.findOne({ projectName: 1 }).sort(viewCount, -1).run( 
       function(err, viewCOunt) {
         var max = viewCount;
    });

Upvotes: 3

Views: 10065

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312105

To get the top 5 articles for project 'name' by viewCount:

ProjectModel.find({projectName: 'name'}).sort({viewCount: -1}).limit(5).exec( 
    function(err, projects) {
        ...
    }
);

Upvotes: 9

Related Questions