3

The .sort() function doesn't seem to work for me at all, it doesn't sort whatever I do.

I display the output via Handlebars {{Book}}

router.get("/", (req, res) => {
  Book.find({ _id: req.params.id })

    .sort({ 'chapters.orderIndex': 1 }) //wont sort 

    .then(books => {
      res.render("books/index", {
        books: books
      })
    });
});

I Also tried:

.sort({ 'Book.chapters.orderIndex': 1 }) 

.sort({ 'Book.date': 1 })

.sort({ 'date': 1 }) //field from Book

.sort({ date: 1 })

and also tried asc/desc instead using 1/-1

Any idea why .sort() isn't working?

skylake
  • 409
  • 2
  • 9
  • 24

1 Answers1

6

See Mongoose Docs:

http://mongoosejs.com/docs/promises.html#queries-are-not-promises

Mongoose queries are not promises. They have a .then() function for co and async/await as a convenience. If you need a fully-fledged promise, use the .exec() function.

So in order to establish the above mentioned promise execution, take a look at the example code below:

router.get("/", (req, res) => {

    let query = Book.find({ _id: req.params.id })
    .sort({ 'chapters.orderIndex': 1 });

    let promise = query.exec();

    promise.then(books => {
        res.render("books/index", {
            books: books
        })
    });
});
Omer Gurarslan
  • 979
  • 11
  • 15