从mongoDB集合中获取N条最新记录时的回调函数[重复]

Posted

技术标签:

【中文标题】从mongoDB集合中获取N条最新记录时的回调函数[重复]【英文标题】:Callback function when fetching N latest records from mongoDB collection [duplicate] 【发布时间】: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() 调用上运行多个函数,我该如何异步执行此操作?谢谢。

【问题讨论】:

【参考方案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 有助于提高代码的可读性。

以上是关于从mongoDB集合中获取N条最新记录时的回调函数[重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何使用Java从mongodb获取最后插入的N条记录?

如何使用Java从mongodb获取最后插入的N条记录?

使用limit和skip从mongoDB中的两个集合中获取记录

如何将内部回调的结果传递给其父函数? [复制]

Node.js 中的回调地狱

Meteor mongodb:如何获取第 N 条记录?