2

I'm trying to sort the data with nested field, called orderIndex.

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

    .sort({ 'Book.chapters.orderIndex': "asc" }) //doesn't work

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

Example of what a Book looks:

//Book
    {
        "_id": {
            "$oid": "1234517fe46cf86900af82f"
        },
        "chapters": [
            {                 
                "_id": {
                    "$oid": "a1"
                },
               "title": "first book",
               "orderIndex": "1",
            },
             {                 
                "_id": {
                    "$oid": "5678798be6bb05e4427ee65"
                },
               "title": "second book",
               "orderIndex": "2",
            },
            //..some more
        ]
    }
skylake
  • 409
  • 2
  • 9
  • 24

1 Answers1

11

Change

.sort({ 'Book.chapters.orderIndex': "asc" })

To

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

Take a look at this link

Here the sort documentation.

Alejandro Montilla
  • 2,626
  • 3
  • 31
  • 35
  • 1
    Unfortuantely this is not working for me :/ https://stackoverflow.com/questions/64673548/sort-query-results-based-desc-value-of-nested-subdocument-within-array-mongoose – insivika Nov 04 '20 at 04:37