How to sort in mongoose?

How to sort in mongoose?

 

Asked on October 24, 2018 in node.js.
Add Comment


  • 4 Answer(s)

    Sort to work in mongoose 2.3.0

    // Find First 10 News Items
    News.find({
        deal_id:deal._id // Search Filters
    },
    ['type','date_added'], // Columns to Return
    {
        skip:0, // Starting Row
        limit:10, // Ending Row
        sort:{
            date_added: -1 //Sort by Date Added DESC
        }
    },
    function(err,allNews){
        socket.emit('news-load', allNews); // Do something with the array of 10 objects
    })
    
    Answered on October 24, 2018.
    Add Comment

    A sort can be done in any of the following ways in mongoose:

    Post.find({}).sort('test').exec(function(err, docs) { ... });
    Post.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
    Post.find({}).sort({test: 1}).exec(function(err, docs) { ... });
    Post.find({}, null, {sort: {date: 1}}, function(err, docs) { ... });
    

     

    Answered on October 24, 2018.
    Add Comment

    This will be useful:

    Post.find().sort([['updatedAt', 'descending']]).all(function (posts) {
        // do something with the array of posts
    });
    

     

    Answered on October 24, 2018.
    Add Comment

    // Find First 10 News Items
    News.find({
    deal_id
    :deal._id // Search Filters
    },
    [‘type’,‘date_added’], // Columns to Return
    {
    skip
    :0, // Starting Row
    limit
    :10, // Ending Row
    sort
    :{
    date_added
    : 1 //Sort by Date Added DESC
    }
    },
    function(err,allNews){
    socket
    .emit(‘news-load’, allNews); // Do something with the array of 10 objects
    })

    Answered on February 21, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.