Search code examples
node.jsreactjsmongodbmongoosemongoose-schema

In MongoDB how do I sort an object based on their values?


Book is a collection that has the option to be voted on by the user. When the user clicks a like button on the client side the vote is increased by 1. I'd like the collection to be sorted in descending order based on the number of votes and this being reflected on the front end.

The votes are being updated and shown on the front end, I'm just not getting the sort functionality to work.

update: function (req, res) {
    console.log("this is reqbody" + JSON.stringify(req.body))
    db.Book
      .findOne({ bookID: req.body.bookID }, (err, result) => {
        console.log(result);
        console.log(result.vote)
        // let voted = result.vote + 1;
        db.Book.updateOne({ _id: result._id }, { vote: result.vote + 1 })
        
        db.Book.find({}).sort({vote: 'decending'}).exec(function(err, docs)
{
        })
        .then(dbModel => {
            console.log(JSON.stringify(dbModel))
            res.json(dbModel)
          }
          )
      }
      )
  },

Solution

  • According to documentation you should use 1 and -1 for ordering your order in sort() mongodb calls.

    Specify in the sort parameter the field or fields to sort by and a value of 1 or -1 to specify an ascending or descending sort respectively.

    db.Book.find({}).sort({vote: -1})