Need help, code seems right but still getting error when i test user-report

this is my pipeline :-

  // TODO Ticket: User Report
      // Return the 20 users who have commented the most on MFlix.
      const pipeline = [
        { $group: { _id: "$email", count: { $sum: 1 } } },
        { $sort: { count: -1 } },
        { $limit: 20 },
      ]

      // TODO Ticket: User Report
      // Use a more durable Read Concern here to make sure this data is not stale.
      const readConcern = comments.readConcern

      const aggregateResult = await comments.aggregate(pipeline, {
        readConcern,
      })

and here is the error from the test :-

> server@1.0.0 test
> jest --passWithNoTests "user-report"

Determining test suites to run...Setup Mongo Connection
(node:2485) Warning: Accessing non-existent property 'count' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
(node:2485) Warning: Accessing non-existent property 'findOne' of module exports inside circular dependency
(node:2485) Warning: Accessing non-existent property 'remove' of module exports inside circular dependency
(node:2485) Warning: Accessing non-existent property 'updateOne' of module exports inside circular dependency
(node:2485) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to MongoClient.connect.
 FAIL  test/user-report.test.js
  User Report
    ✓ Should return exactly twenty results (72ms)
    ✕ Should return correct comment totals (71ms)

  ● User Report › Should return correct comment totals

    expect(received).toEqual(expected) // deep equality

    - Expected
    + Received

      Object {
        "_id": "roger_ashton-griffiths@gameofthron.es",
    -   "count": 331,
    +   "count": 277,
      }

      14 |     const userReport = await CommentsDAO.mostActiveCommenters()
      15 |     const topCommenter = userReport[0]
    > 16 |     expect(topCommenter).toEqual({
         |                          ^
      17 |       _id: "roger_ashton-griffiths@gameofthron.es",
      18 |       count: 331,
      19 |     })

      at toEqual (test/user-report.test.js:16:26)
      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)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        0.878s, estimated 1s
Ran all test suites matching /user-report/i.
Teardown Mongo Connection

any help much appreciated !

1 Like

Hi @Dave_Clarke, welcome to the community.
I get the correct answer when running the same query like yours, below is the screenshot of the same.

Having said that, seems like your data may have got modified while performing the other exercises, I would recommend you to refresh you sample data set as mentioned in this FAQ Post Question 5.

I hope it helps.
In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

I’ve refreshed the data set as you suggested, but still getting the error.

any other ideas ?

Hi Sourabh, I, as well as many other students, are getting errors when running the user report test. I have a pipeline setup the same way and I’m still getting errors: User Report
✕ Should return exactly twenty results (29ms)
✕ Should return correct comment totals (4ms)

● User Report › Should return exactly twenty results

expect(received).toBe(expected) // Object.is equality

Expected: 20
Received: undefined

   8 |   test("Should return exactly twenty results", async () => {
   9 |     const userReport = await CommentsDAO.mostActiveCommenters()
> 10 |     expect(userReport.length).toBe(20)
     |                               ^
  11 |   })
  12 | 
  13 |   test("Should return correct comment totals", async () => {

  at toBe (test/user-report.test.js:10:31)
  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 processTicksAndRejections (node:internal/process/task_queues:94:5)

● User Report › Should return correct comment totals

expect(received).toEqual(expected) // deep equality

Expected: {"_id": "roger_ashton-griffiths@gameofthron.es", "count": 331}
Received: undefined

  14 |     const userReport = await CommentsDAO.mostActiveCommenters()
  15 |     const topCommenter = userReport[0]
> 16 |     expect(topCommenter).toEqual({
     |                          ^
  17 |       _id: "roger_ashton-griffiths@gameofthron.es",
  18 |       count: 331,
  19 |     })

  at toEqual (test/user-report.test.js:16:26)
  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 processTicksAndRejections (node:internal/process/task_queues:94:5)

console.error src/dao/commentsDAO.js:142
Unable to retrieve most active commenters: TypeError: comments.readConcern is not a function

console.error src/dao/commentsDAO.js:142
Unable to retrieve most active commenters: TypeError: comments.readConcern is not a function

Test Suites: 1 failed, 1 total
Tests: 2 failed, 2 total
Snapshots: 0 total
Time: 1.5s, estimated 3s
Ran all test suites matching /user-report/i.
Teardown Mongo Connection
Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren’t stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue.

I have also refreshed my dataset and still get the same errors. Has the dataset been completely modified? Also, at the beginning of the course the instructor says that the mflix app is a React app, yet I don’t see React installed in the package.json. This entire project needs to be revamped to actually use React either through create-react-app or a JAMStack application like Gatsby.js or Next.js.

The other in this thread are not experiencing the same error as yours. @Dave_Clarke is having the wrong count in his result set. But your code returns undefined rather than a result set. Share your code so that we see what is going wrong.

1 Like
static async mostActiveCommenters() {
    /**
    Ticket: User Report

    Build a pipeline that returns the 20 most frequent commenters on the MFlix
    site. You can do this by counting the number of occurrences of a user's
    email in the `comments` collection.
    */
    try {
      // TODO Ticket: User Report
      // Return the 20 users who have commented the most on MFlix.
      const groupStage = { $group: { _id: "$email", count: { $sum: 1 } } }
      const sortStage = { $sort: { count: -1 } }
      const limitStage = { $limit: 20 }
      const pipeline = [groupStage, sortStage, limitStage]

      // TODO Ticket: User Report
      // Use a more durable Read Concern here to make sure this data is not stale.
      const readConcern = comments.readConcern("local")

      const aggregateResult = await comments.aggregate(pipeline, {
        readConcern: { level: "majority" },
      })
      console.log(aggregateResult.count())
      console.log(readConcern)
      return await aggregateResult.toArray()
    } catch (e) {
      console.error(`Unable to retrieve most active commenters: ${e}`)
      return { error: e }
    }
  }
}

I see that my error did not fully show, so here is a screenshot of the Full error :-

Hi @Dave_Clarke,
That’s really strange. Can you provide me your connection string in Direct Message?

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

Your code crash at the line

and from the error message

it means that you are not setting the read concern with the appropriate function.

1 Like

According to the MongoDB documentation for v. 3.6 and above, this should be the correct way to setup the pipeline with the readConcern, so my code now looks like:

static async mostActiveCommenters() {
    /**
    Ticket: User Report

    Build a pipeline that returns the 20 most frequent commenters on the MFlix
    site. You can do this by counting the number of occurrences of a user's
    email in the `comments` collection.
    */
    try {
      // TODO Ticket: User Report
      // Return the 20 users who have commented the most on MFlix.
      const groupStage = { $group: { _id: "$email", count: { $sum: 1 } } }
      const sortStage = { $sort: { count: -1 } }
      const limitStage = { $limit: 20 }
      const pipeline = [groupStage, sortStage, limitStage]

      // TODO Ticket: User Report
      // Use a more durable Read Concern here to make sure this data is not stale.
      const readConcern = comments.readConcern

      const aggregateResult = await comments.aggregate(pipeline, {
        readConcern: { level: "majority" },
      })
      console.log(aggregateResult.count())
      console.log(readConcern)
      return await aggregateResult.toArray()
    } catch (e) {
      console.error(`Unable to retrieve most active commenters: ${e}`)
      return { error: e }
    }
  }

I rerun the tests and it still fails.

What error do you get now that you have change your code from

to

npm test -t user-report

server@1.0.0 test
jest --passWithNoTests “user-report”

Determining test suites to run…Browserslist: caniuse-lite is outdated. Please run next command npm update
Setup Mongo Connection
(node:3379) Warning: Accessing non-existent property ‘count’ of module exports inside circular dependency
(Use node --trace-warnings ... to show where the warning was created)
(node:3379) Warning: Accessing non-existent property ‘findOne’ of module exports inside circular dependency
(node:3379) Warning: Accessing non-existent property ‘remove’ of module exports inside circular dependency
(node:3379) Warning: Accessing non-existent property ‘updateOne’ of module exports inside circular dependency
(node:3379) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to MongoClient.connect.
console.error src/dao/commentsDAO.js:142
Unable to retrieve most active commenters: MongoError: count can only be used with find command

console.error src/dao/commentsDAO.js:142
Unable to retrieve most active commenters: MongoError: count can only be used with find command

FAIL test/user-report.test.js
User Report
✕ Should return exactly twenty results (74ms)
✕ Should return correct comment totals (5ms)

● User Report › Should return exactly twenty results

expect(received).toBe(expected) // Object.is equality

Expected: 20
Received: undefined

   8 |   test("Should return exactly twenty results", async () => {
   9 |     const userReport = await CommentsDAO.mostActiveCommenters()
> 10 |     expect(userReport.length).toBe(20)
     |                               ^
  11 |   })
  12 | 
  13 |   test("Should return correct comment totals", async () => {

  at toBe (test/user-report.test.js:10:31)
  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 processTicksAndRejections (node:internal/process/task_queues:94:5)

● User Report › Should return correct comment totals

expect(received).toEqual(expected) // deep equality

Expected: {"_id": "roger_ashton-griffiths@gameofthron.es", "count": 331}
Received: undefined

  14 |     const userReport = await CommentsDAO.mostActiveCommenters()
  15 |     const topCommenter = userReport[0]
> 16 |     expect(topCommenter).toEqual({
     |                          ^
  17 |       _id: "roger_ashton-griffiths@gameofthron.es",
  18 |       count: 331,
  19 |     })

  at toEqual (test/user-report.test.js:16:26)
  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 processTicksAndRejections (node:internal/process/task_queues:94:5)

Test Suites: 1 failed, 1 total
Tests: 2 failed, 2 total
Snapshots: 0 total
Time: 2.526s
Ran all test suites matching /user-report/i.
Teardown Mongo Connection
Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren’t stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue.

The error message

tells us that the line below is wrong.

Just remove it and if you want to log the count do it using the array you get with toArray().

I removed the console.log statements and reran the test. It now fails only one test:

FAIL test/user-report.test.js
User Report
✓ Should return exactly twenty results (248ms)
✕ Should return correct comment totals (184ms)

● User Report › Should return correct comment totals

expect(received).toEqual(expected) // deep equality

- Expected
+ Received

  Object {
    "_id": "roger_ashton-griffiths@gameofthron.es",
-   "count": 331,
+   "count": 277,
  }

  14 |     const userReport = await CommentsDAO.mostActiveCommenters()
  15 |     const topCommenter = userReport[0]
> 16 |     expect(topCommenter).toEqual({
     |                          ^
  17 |       _id: "roger_ashton-griffiths@gameofthron.es",
  18 |       count: 331,
  19 |     })

  at toEqual (test/user-report.test.js:16:26)
  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 processTicksAndRejections (node:internal/process/task_queues:94:5)

Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 passed, 2 total
Snapshots: 0 total
Time: 1.352s, estimated 2s
Ran all test suites matching /user-report/i.
Teardown Mongo Connection

I tried grouping on the email and name fields and I’m still getting a count of 277 instead of 331. Was there a change in the data?

1 Like

2 user @joyfulnoiseforyahshu and @Dave_Clarke with the same failed test with the same count. There is something in there. So I create a new cluster, loaded the sample data set AND roll the drums … the new correct answer should be 277.

So

yes there was a change in the data.

1 Like

Hi @joyfulnoiseforyahshu, @Dave_Clarke, @steevej thank you for flagging this.
I have forwarded this issue to the appropriate team, please be rest assured that our team is working on it and will get back to you with an update on this ASAP.

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

4 Likes

Hi everyone, this is to update you all, that we are working on fixing the issue, and we will hopefully reset the dataset by the end of this week.
In case you have no attempts remaining for the concerned question, please let me know through DM and I will give you the required credits for the exercise.

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

3 Likes