Javascript-猫鼬:按嵌套字段排序

这个问题已经在这里有了答案:            >            how to sort array inside collection record in mongoDB                                    14个
>            MongoDB sort documents by array elements                                    1个
我正在尝试使用称为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
      })
    });
});

一本书的外观示例:

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

解决方法:

更改

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

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

看看这个link

这里是sort文档.

上一篇:javascript-Express / Mongoose路由器:对于路径“ _id”的值“ undefined”,未能成功转换到ObjectId


下一篇:javascript-查询比较对象数组