Mongoose: Trier par champ nested

J’essaie de sortinger les données avec un champ nested, appelé 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 }) }); }); 

Exemple d’apparence d’un Book :

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

Changement

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

À

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

Regardez ce lien

Voici la documentation de sort .