[英]Mongodb: last N records, skip collection size - 30?
Simple: 简单:
models.Message.find({ chat_id: req.params.chat_id }).skip(80).limit(30).sort({sent:1}).exec(function(err, message) {
if(err) {
res.json({error: 'Message not found.'});
} else {
res.json(message);
}
});
How can I write skip()
to skip the entire collection minus the last 30, making it dynamic? 我如何编写
skip()
来跳过整个集合减去最后30个,从而使其具有动态性?
Detail: 详情:
The reason I need to do this is because it's a chat app, and the messages need to return oldest to newest hence sort({sent:1})
but the collection can get big and I only want to send 30 documents. 我需要执行此操作的原因是因为它是一个聊天应用程序,并且消息需要从最旧的返回到最新的消息,因此需要
sort({sent:1})
但集合可能很大,我只想发送30个文档。
So for example 所以举个例子
[
{sent: 1, message:'hey'},
{sent: 2, message:'sup'},
{sent: 3, message:'nttn much'}
]
For this example I want to send 1 message to the client, statically it could look like this. 对于此示例,我想向客户端发送1条消息,静态地看起来像这样。
models.Message.find({ chat_id: req.params.chat_id }).skip(2).limit(1).sort({sent:1}).exec(function(err, message) {
if(err) {
res.json({error: 'Message not found.'});
} else {
res.json(message);
}
});
That will return the latest {sent: 3, message:'nttn much'}
, this is good. 那会返回最新的
{sent: 3, message:'nttn much'}
,这很好。
BUT without the skip method it would look like this 但是如果没有skip方法,它将看起来像这样
models.Message.find({ chat_id: req.params.chat_id }).limit(1).sort({sent:1}).exec(function(err, message) {
if(err) {
res.json({error: 'Message not found.'});
} else {
res.json(message);
}
});
returning this to the client {sent: 1, message:'hey'}
, not so good. 将此返回给客户
{sent: 1, message:'hey'}
,不是很好。
So obviously I need to skip, I need to do more scouring on the mongoDB docs, but there has to be a way to check the collection length then minus x
or in this case about 30, then pass that in to skip()
? 因此,显然我需要跳过,我需要在mongoDB文档上进行更多的搜索,但是必须有一种方法来检查集合长度,然后减去
x
或在这种情况下约为30,然后将其传递给skip()
?
Any idea how I do that? 知道我该怎么做吗?
您可以使用skip(80).limit(30).sort({sent:-1})
来获取最后30个文档,然后在您的客户端应用中以所需的方式对其进行排序。
So I realized I can work with the object after querying the DB before doing res.json
and sending to the client. 因此,我意识到在查询
res.json
之后,可以在执行res.json
并将其发送给客户端之前使用该对象。 Here is what I came up with, and seems to work as of now. 这是我想出的,现在似乎可以使用。
getById: function(req, res) {
if (req.user) {
models.Message.find({ chat_id: req.params.chat_id }).sort({sent:1}).exec(function(err, message) {
if(err) {
res.json({error: 'Message not found.'});
} else {
console.log(message.length);
message = message.slice(message.length - 30);
console.log(message);
res.json(message);
}
});
}
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.