简体   繁体   中英

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?


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.

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.

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.

BUT without the skip method it would look like this

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.

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() ?

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. 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);
            }
        });
    }
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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