Alexander Miller
Alexander Miller

Reputation: 73

Can I query MongoDB in reverse order?

I have a route that handles requests for posts by a certain user. I want each request to serve the latest 25 posts matching the given author, and on the next request serve the 25 after that. My code so far:

router.get('/profile/:id', (req, res) => {
 Post.find({'author': req.params.id})
  .skip(req.query.skip)
  .limit(25)
  .populate({
    path: 'author',
    select: 'firstName lastName img'
  }).then(
    posts =>{
      res.json({posts: modifyPosts(posts, req.user._id)})
    }
  ).catch(
    err => {
      console.log(err)
      res.json({err: err})
    }
  )
})

I want to serve the newest posts first, and serve older documents to the client later. "req.query.skip" is incremented on the client side before each request. If I understand correctly, adding the .sort("date") method will still return the same 25 documents. The code I have written always returns the oldest 25 documents first, so I guess am basically looking for an option that will let me search the database from the bottom up.

Upvotes: 3

Views: 13009

Answers (2)

Xplod
Xplod

Reputation: 43

You could do something like below in GET request APIs:

db.collection.find().sort({ _id: -1 }, function(err, docs){
            console.log(docs);
            res.json(docs);
        });

Hope this helps! Thanks.

Upvotes: 2

Khay
Khay

Reputation: 1570

If you want to get the newest posts first you need to use .sort({ date: -1 }) or .sort('-date') in mongoose query.

UPDATED

If you are using .populate(), sort should be inside populate.

.populate({
    path: 'author',
    select: 'firstName lastName img',
    options: { sort: { 'date': -1 }}
  }

Upvotes: 3

Related Questions