我有一个包含多个项目的网站。并且每个项目都有不同的视图数。
我想要做的是按此顺序检索前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");
}
});
}
以下是我尝试按此顺序[max, max-1, max-2, max-3, max-4]
检索前5个观看文章的数组。请记住,文章可以实时查看排名变化。
// 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;
});
答案 0 :(得分:6)
要按viewCount
获取项目“名称”的前5篇文章:
ProjectModel.find({projectName: 'name'}).sort({viewCount: -1}).limit(5).exec(
function(err, projects) {
...
}
);