【问题标题】:Callback function when fetching N latest records from mongoDB collection [duplicate]从mongoDB集合中获取N条最新记录时的回调函数[重复]
【发布时间】:2020-12-11 09:12:55
【问题描述】:

我在编写用于从 mongoDB 集合中获取最新 N 条记录的回调时遇到问题。我正在创建一个名为 /pp 的 Express 路由,它将在我的数据库中返回内容。我以前只是返回其中的所有内容,因此类似于:

app.get("/pp", function (req, res) {
  PPOverTime.find({}, function (error, documents) {
      res.send(documents);
    });
});

(PPovertime 是我收藏的名字)

但我现在想将最后 N 条记录放入数据库,根据上面链接的 Stack Overflow 帖子,这是通过 "db.foo.find().sort({_id:-1}).limit 完成的(30)" 例如最后 30 个条目。

那么我在哪里放置回调函数来返回响应呢?我试过了:

app.get("/pp", function (req, res) {
  PPOverTime.find()
    .limit(30)
    .sort({ _id: -1 }, function (error, documents) {
      res.send(documents);
    });
});

但这会产生错误,因为排序函数只能接受一个参数。我想更一般地说,如果我在 find() 调用上运行多个函数,我该如何异步执行此操作?谢谢。

【问题讨论】:

    标签: javascript mongodb express mongoose


    【解决方案1】:

    你可以试试这个吗?

    app.get("/pp", function (req, res) {
      PPOverTime.find()
        .limit(30)
        .sort({ _id: -1 })
        .then(results => {
          console.log(results)
        })
        .catch(error => console.error(error))
    }
    

    【讨论】:

    • 这返回了一个错误,说“TypeError: PPOverTime.find(...).limit(...).sort(...).toArray is not a function”
    • 尝试删除 toArray() 并尝试。它有效。
    【解决方案2】:

    谢谢大家,我就是这样做的。

    // limit to returning only the last 20 entries
    app.get("/pp", function (req, res) {
      let q = PPOverTime.find().limit(20).sort({ _id: 1 });
      q.exec(function (err, data) {
        res.send(data);
      });
    });

    【讨论】:

    • 我觉得 exec 是一种使用回调的老方法。 [then and catch] 即 Promises 有助于提高代码的可读性。
    猜你喜欢
    • 2012-06-10
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    相关资源
    最近更新 更多