M220JS - Error in sorting exercise

Hi.

I having an error that i can’t find when sorting data by date. Could you give me a hand, please?

Here is my code:

Ticket: Get Comments

   const pipeline = [
        {
          '$match': {
            '_id': new ObjectId(id)
          }
        }, 
        {
          '$lookup': {
            'from': 'comments', 
            'localField': '_id', 
            'foreignField': 'movie_id', 
            'as': 'comments'
          }
        }, 
        {
          '$sort': {
            'coments.date': -1
          }
        }
      ]

thank you in advance.

Typing error. You spelled coments. You are missing an m.

1 Like

Hi, i have corrected coments, but it still doesn’t work. Error is:

● Get Comments › comments should be sorted by date

  at assertions (test/get-comments.test.js:17:12)
  at tryCatch (node_modules/regenerator-runtime/runtime.js:45:40)
  at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:271:22)      
  at Generator.prototype.<computed> [as next] (node_modules/regenerator-runtime/runtime.js:97:21)
  at asyncGeneratorStep (node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)       
  at _next (node_modules/@babel/runtime/helpers/asyncToGenerator.js:25:9)
  at node_modules/@babel/runtime/helpers/asyncToGenerator.js:32:7
  at Object.<anonymous> (node_modules/@babel/runtime/helpers/asyncToGenerator.js:21:12)

This is the new code (corrected):

      const pipeline = [
        {
          '$match': {
            '_id': new ObjectId(id)
          }
        }, 
        {
          '$lookup': {
            'from': 'comments', 
            'localField': '_id', 
            'foreignField': 'movie_id', 
            'as': 'comments'
          }
        }, 
        {
          '$sort': {
            'comments.date': -1
          }
        }
      ]

You have to sort the comments inside the movie. Now, the $sort is in the scope of the movie. You have to sort inside the $lookup. Look at https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/ and you will see a variant of $lookup that allows a pipeline in the looked (comments in this case) collection.

2 posts were split to a new topic: Whenever I put a pipeline in $lookup I get zero comments from the merge