Mongoose: Sort by nested field [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:43:01

问题:

This question already has an answer here:

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         ]     } 

回答1:

Change

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

To

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

Take a look at this link

Here the sort documentation.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!