2

複数のプロジェクトを持つサイトがあります。また、プロジェクトごとにビュー数が異なります。私がやりたいことは、上位 5 つの表示されたプロジェクトの配列をこの順序で取得することです[max, max-1, max-2, max-3, max-4].

スキーマは次のとおりです。

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


}

以下は、上位 5 つの閲覧記事の配列をこの順序で取得する試み[max, max-1, max-2, max-3, max-4]です。記事の閲覧順位はリアルタイムで変動しますのでご了承ください。

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

SQL バージョン:

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

マングースのバージョン:

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

1 に答える 1

8

プロジェクト 'name' の上位 5 件の記事を取得するにはviewCount:

ProjectModel.find({projectName: 'name'}).sort({viewCount: -1}).limit(5).exec( 
    function(err, projects) {
        ...
    }
);
于 2012-11-08T19:39:03.283 に答える