【问题标题】:How can I sort and limit with Mongoose如何使用 Mongoose 进行排序和限制
【发布时间】:2019-01-31 12:35:39
【问题描述】:

我使用 Express 和 Mongoose 制作了一个评论应用。我有一个如下的评论模型:

var mongoose = require('mongoose');

var ReviewSchema = mongoose.Schema({
    title: String,
    description: String,
    rating: Number
}, {
    timestamps: true
}
);

module.exports = mongoose.model('Review', ReviewSchema);

在我的控制器中,我只得到如下所有评论列表。但现在我想获得一个包含 10 条最近评论和排序方式(orderby 时间戳)的列表。我怎么能用猫鼬做到这一点?请帮我!我是 NodeJS 和 Mongodb 的新手。

exports.findAll = function(req, res) {
    console.log("Fetching Review...")
    // Retrieve and return all reviews from the database.
     Review.find(function(err, reviews){
        if(err) {
            console.log(err);
            res.status(500).send({message: "Some error occurred while retrieving Review."});
        } else {
            res.send(reviews);
        }
    });
};

非常感谢

【问题讨论】:

  • 试试这个Review.find({}).sort({ createdAt: 1 }).limit(10)
  • 这行不通,安东尼·温兹莱特

标签: node.js mongodb express mongoose


【解决方案1】:

你可以这样试试:

Review.find({}, function(err,reviews){}).sort({_id: -1}).limit(10);

【讨论】:

    【解决方案2】:

    这应该适合你:

    Review.find()
      .sort({_id: -1})
      .limit(10)
      .then(reviews => {
        console.log(reviews)
      });
    

    【讨论】:

    • 太棒了。谢谢。您应该标记答案,希望它可以帮助其他人。
    猜你喜欢
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 2017-10-22
    • 2012-05-11
    • 2012-05-09
    • 2017-05-23
    • 2020-04-23
    • 1970-01-01
    相关资源
    最近更新 更多