我有一个包含多个项目的网站。每个项目都有不同的观看次数。我想要做的是按此顺序检索前 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;
});