0

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)
          }
          )
      }
      )
  },
Dom
  • 39
  • 1
  • 9
  • instead of doing findOne and then update. You should do findOneAndUpdate and use $inc operator to increment vote. – Yahya Sep 22 '20 at 15:47
  • Does this answer your question? [In Mongoose, how do I sort by date? (node.js)](https://stackoverflow.com/questions/5825520/in-mongoose-how-do-i-sort-by-date-node-js) – Alex Blex Sep 22 '20 at 15:49

1 Answers1

1

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})
akazakou
  • 175
  • 2
  • 7
  • 1
    Thanks, for pointing this out. Completely overlooked this in the documentation. Was able to get it work using the value -1. – Dom Sep 23 '20 at 17:53