I
I
IDONTSUDO2019-12-27 11:24:01
MongoDB
IDONTSUDO, 2019-12-27 11:24:01

MongoDB get last added document?

There is such a code. In short, I'm making chats and I need to get 10 user dialogs and find the last message in each dialog. The problem is that, I need to do this in a limited way, but not from the beginning of the document.

exports.ChanelList = async (req, res) =>{
    let userId = req.body.userId
    const currentPage = req.query.page || 1
    const perPage = 10
    var totalItems

    const chanels = await Chanel.find({User:userId})

        .countDocuments()
        .then(count => {
            totalItems = count;
            return Chanel.find({User:userId})
                .skip((currentPage - 1) * perPage)
                .limit(perPage)
         
        })
        .then(data => {
              let promises = data.map(one => Message.find({DialogId:one._id})
              .limit(1)
              .then(data =>{ return ({message:data,dialog:one})}));
              
        
              Promise.all(promises)
                .then(responses =>  res.status(200).json(requests))

        })
        .catch(err => console.log(err))
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
IDONTSUDO, 2019-12-27
@IDONTSUDO

.sort({'_id':-1}).limit(1)
found such a solution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question