如何用非空数组对数据库排序?

时间:2019-02-12 14:17:18

标签: javascript arrays mongodb

我的MongoDB中有很多评论。我需要按createdAt对其进行排序,但应该只包含评论的评论

我有一段已经存在的代码

    const getSortingQuery = _.cond([
  [
    _.isEqual('relevance'),
    () => [
      {
        $addFields: {
          relevance: {
            $reduce: {
              input: '$votes',
              initialValue: 0,
              in: {
                $sum: [
                  {
                    $cond: [
                      {
                        $eq: ['$$this.value', 'like']
                      },
                      1,
                      -1
                    ]
                  },
                  '$$value'
                ]
              }
            }
          }
        }
      },
      {
        $sort: {
          relevance: -1,
          createdAt: -1
        }
      }
    ]
  ],
  [() => true, () => [{ $sort: { createdAt: -1 } }]]
]);

我要粘贴如下所示的代码

[ 
   _.isEqual('replied'),
   () => [
    {
     $project: {
          comments: {
            $filter: {
              input: "$comments",
              cond: { $exists: true, $ne: [] }
            }
          }
        }
       },
      { $sort: { createdAt: -1 } }
    ]
  ],

现在看来它不起作用了,所以我请您帮忙。

实际上评论的例子是这样的

    reviews: [
    {
    author: {
    name: string,
    email: string,
    role: string,
    reviews: number,
    },
    score: {
    overall: number,
    },
    votes: {
    vote: boolean,
    like: {
    count: number,
    },
    dislike: {
    count: number,
    }
    },
    status: string,
    text: string,
    comments: [
    {
    text: string,
    }
    ],
     createdAt: {
          type: Date,
          default: () => new Date()
        }
}
    ]

0 个答案:

没有答案