0

I've created a route in a Node.js project to render all "logs" from a MongoDB database to a Web page:

   app.get('/api/logs', function (req, res) {
    Log.find( function (err, logs) {
     res.json(logs);
    });
   });

I want to modify this query to (1) limit the response to 10 logs and (2) display the logs in reverse chronological order (from most recent to least recent). If I try the below code, nothing will render to my page and my Node server gives the following error: Error: sort() only takes 1 Argument.

   app.get('/api/logs', function (req, res) {
    Log.find().limit(10).sort({$natural:-1}, function(err, logs){
     res.json(logs);
    });
   });

The above snippet DOES work if I type it directly into my Monog console as a single query: Log.find().limit(10).sort({$natural:-1}) Is there a different way to write this to grab the information I want? Thanks for your suggestions!

3
  • sort gets one object, you ma place its keys separated with comma Commented Jul 23, 2015 at 23:03
  • You should look into using something like Mongoose to help manage mongo. It'll make your life much easier. Commented Jul 23, 2015 at 23:34
  • $natural refers to the order of documents "as they appear" on disk ( citation in the link ), therefore is likely not what you want. A better indicator or "creation" is to create a "timestamp" field with the creation date, or just use the immutable _id field, contains a timestamp and sorts accordingly. Log.find().sort({ "_id": -1 }).limit(10),function(err,logs) { ... }) Commented Jul 23, 2015 at 23:52

1 Answer 1

1

This works perfectly:

app.get('/api/logs', function (req, res) {
    Log.find().limit(10).sort(-fieldToSort).exec(function(err, logs){
        res.send(logs)
    })
   });

The -fieldToSort sorts the field in a descending order as you requested. fieldToSort is the field name you want to sort.

Hope it helps!

Sign up to request clarification or add additional context in comments.

1 Comment

You can see more of this query methods here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.