将Mongoose find()与sort()和limit()结合使用

我想获取部分数据,并且可以正常工作,但是当我尝试使用limit()和sort()查询时,它不起作用。

我想按日期对五个数据进行排序。并且应该仅是“ login bio avatar_url”数据。减少数据。

但是也没有错误消息,因此我找不到错误的出处。

[我的代码]

let User = require('../lib/models/userModel');
router.get("/", function (req, res, next) {
  console.log(`HOME ROUTE!`);
  User.find({}).limit(5).sort({
    created_at: -1
  }), 'login bio avatar_url', (function (err, result) {
    if (err) return handleError(err);
    console.log(result);
    res.render('main', {
      dataarray: result,
      _user: req.user
    })
  })
});

我的数据结构如下所示。

[数据]

{
    "_id": {
        "$oid": "5ebbcc92ae44dd149c12faf3"
    },
    "login": "apple",
    "id": 10639145,
    "node_id": "MDEyOk9yZ2FuaXphdGlvbjEwNjM5MTQ1",
    "avatar_url": "https://avatars0.githubusercontent.com/u/10639145?v=4",
~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Cut useless data]
    "name": "Apple",
    "company": null,
    "blog": "https://apple.com",
    "location": "Cupertino, CA",
    "email": null,
    "hireable": null,
    "bio": null,
    "public_repos": 85,
    "public_gists": 0,
    "followers": 0,
    "following": 0,
    "created_at": "2015-01-21T20:19:28Z",
    "updated_at": "2020-05-01T14:38:33Z"
}

When I tried to access / path, console only shows the this log.
enter image description here

评论
昔其雨
昔其雨

用此代码解决。我认为是顺序问题

let User = require('../lib/models/userModel');
router.get("/", function (req, res, next) {
  console.log(`HOME ROUTE!`);
  User.find({},'login bio avatar_url', {limit:5}).sort({created_at:-1}).exec(function (err, result) {
    if (err) console.log(err);
    console.log(result);
    res.render('main', {
      dataarray: result,
      _user: req.user
    })
  })
});
点赞
评论