简体   繁体   English

Node.js Mongo返回带有分页信息的数据

[英]Nodejs mongo return data with pagination information

I am using node and mongo with the native client. 我正在使用node和mongo与本机客户端。

I would like to add pagination to my application. 我想在我的应用程序中添加分页。

To get pagination, I need my responses to always return count alongside data 要获得分页,我需要我的回复始终将countdata一起返回

I would like to get something like: 我想得到类似的东西:

{
   count : 111, 
   data : [ { 'a' : 'only first item was requested' } ]
}

I can do this in mongo 我可以在蒙哥做到这一点

> var guy  = db.users.find({}).limit(1)
> guy.count()
11
> guy.toArray()
[
    {
        "_id" : ObjectId("5381a7c004fb02b10b557ee3"),
        "email" : "myEmail@guy.com",
        "fullName" : "guy mograbi",
        "isAdmin" : true,
        "password" : "fe20a1f102f49ce45d1170503b4761ef277bb6f",
        "username" : "guy",
        "validated" : true
    }
]

but when I do the same with nodejs mongo client I get errors. 但是当我对nodejs mongo client执行相同操作时,会出现错误。

var cursor = collection.find().limit(1);
cursor.toArray( function(){ .. my callback .. });
cursor.count(); 

It seems that 看起来

  • count is not defined on cursor count未在游标上定义
  • that once I applied toArray on cursor, I cannot use the cursor again 一旦在光标上应用了toArray ,就无法再次使用光标

How, using nodejs, can I accomplish the same thing I can with mongo directly? 如何使用nodejs直接在mongo中完成相同的工作?

As others have said, if you want to have a total count of the items and then the data you will need to have two queries, there is no other way. 正如其他人所说,如果要对项目总数进行统计,然后对数据进行两次查询,则别无选择。 Why are you concerned with creating two queries? 为什么要关注创建两个查询?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM