首页 > 解决方案 > 使用 Mongoose 按名称排序根,按位置排序它们的图像

问题描述

我正在制作一个带有 react、graphql、apollo 和 mongoose 的应用程序,我想按名称排序我的数据(在这种情况下没有问题),以及他们自己的一组图像,按位置。我有这样的东西(在伪json中):

{data: 
  {
  name: "Name 3"
  Images:[
    {
      name: "Image 3.22"
      position: 2
    },
    {
      name: "Image 3.91"
      position: 1
    },
    {
      name: "Image 3.73"
    }
  },{
{
  name: "Name 2"
  Images:[
    {
      name: "Image 2.53"
      position: 3
    },
    {
      name: "Image 2.61"
      position: 1
    },
    {
      name: "Image 2.32"
      position: 2
    }
  }

结果必须是:

{data:
  {
  name: "Name 2",
  Images:[
    {
      name: "Image 2.61"
      position: 1
    },
    {
      name: "Image 2.32"
      position: 2
    },
    {
      name: "Image 2.53"
      position: 3
    }]
  },{
  name: "Name 3"
  Images:[
    {
      name: "Image 3.91"
      position: 1
    },
    {
      name: "Image 3.22"
      position: 2
    },
    {
      name: "Image 3.73"
    }]
  }
}

我用return ArticleModel.find(filtro).limit(20).sort({name: "asc", "Images.position": "desc"}).select(projection).exec();,但它是错误的。如果该位置null存在或不存在,则它应该位于图像列表的末尾。有任何想法吗??

标签: mongoose

解决方案


推荐阅读