User Management Ticket - 2 passed, 2 failed

Hey everyone. I need help. I have been trying to solve this ticket for 4 hours now, and I am losing hope.
Whenever I try to implement the loginUser and addUser tickets I run into roadblocks

Here is my addUser() implementation

  static async addUser(userInfo) {
/**
Ticket: Durable Writes

Please increase the durability of this method by using a non-default write
concern with ``insertOne``.
*/

try {
  // TODO Ticket: User Management
  // Insert a user with the "name", "email", and "password" fields.
  let { name, email, password } = userInfo;
  console.log(`${name}, ${email}, ${password}`)
  await users.insertOne(
    {
      name: name,
      email: email,
      password: password
    })

  // TODO Ticket: Durable Writes
  // Use a more durable Write Concern for this operation.
  await users.insertOne({ someField: "someValue" })
  return { success: true }
} catch (e) {
  if (String(e).startsWith("MongoError: E11000 duplicate key error")) {
    return { error: "A user with the given email already exists." }
  }
  console.error(`Error occurred while adding new user, ${e}.`)
  return { error: e }
}

}

Here is my loginUser() implementation.

     static async loginUser(email, jwt) {
    try {
      // TODO Ticket: User Management
      // Use an UPSERT statement to update the "jwt" field in the document,
      // matching the "user_id" field with the email passed to this function.
      await sessions.updateOne(
        { user_id: email },
        { $set: { jwt: jwt } },
        { upsert: true },
      )
    } catch (e) {
      console.error(`Error occurred while logging in user, ${e}`)
      return { error: e }
    }
  }

This little part is beyond me. I have gone through countless posts on the forums but none seem to relate to the errors I am getting.

Here are the errors for each of the implementations respectively:

  ● User Management › it can add a new user to the database

expect(received).toBeTruthy()

Received: undefined

  29 |      */
  30 |     const actual = await UsersDAO.addUser(testUser)
> 31 |     expect(actual.success).toBeTruthy()
     |                            ^
  32 |     expect(actual.error).toBeUndefined()
  33 | 
  34 |     // we should be able to get the user
  at toBeTruthy (test/user-management.test.js:31:28)
  at tryCatch (node_modules/babel-runtime/node_modules/regenerator
-runtime/runtime.js:62:40)
  at Generator.invoke [as _invoke] (node_modules/babel-runtime/nod
e_modules/regenerator-runtime/runtime.js:296:22)
  at Generator.prototype.(anonymous function) [as next] (node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:114:21)
  at step (node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
  at node_modules/babel-runtime/helpers/asyncToGenerator.js:28:13



  ● User Management › it allows a user to login

TypeError: Cannot read property 'success' of undefined

  48 |   test("it allows a user to login", async () => {
  49 |     const actual = await UsersDAO.loginUser(testUser.email, sessionUser.jwt)
> 50 |     expect(actual.success).toBeTruthy()
     |                   ^
  51 |     const sessionResult = await UsersDAO.getUserSession(testUser.email)
  52 |     delete sessionResult._id
  53 |     expect(sessionResult).toEqual(sessionUser)

  at success (test/user-management.test.js:50:19)

I will greatly appreciate any guidance on the above.

Why do you do 2 insertOne in your addUser?

It looks like your loginUser or addUser is not returning a valid object.

Thank you for answering.
The two insertOne() calls in the addUser() function are independent of each other.
The second insertOne() is meant to be used with the next ticket on Durable Writes. I tried deleting the second insertOne() but the result is still the same.

I agree with you that the two functions are returning an unexpected value.
I need help figuring out what they return, and how to avoid the error.

Hi Anthony,

You may not need to add a second insertOne method for the durable writes ticket. There is good documentation on MongoDB on the syntax for write concern.
https://docs.mongodb.com/manual/reference/write-concern/#write-concern-specification

Hope the above makes sense.

2 Likes

the reason why your test might be failing is because you need to first complete the getUserSession() function in order for the loginUser() function to work. You will see that the unit test for loginUser() is calling the getUserSession() - see below test for ease of reference:

     `test("it allows a user to login", async () => {
    const actual = await UsersDAO.loginUser(testUser.email, sessionUser.jwt)
    expect(actual.success).toBeTruthy()
    **const sessionResult = await UsersDAO.getUserSession(testUser.email)**
    delete sessionResult._id
    expect(sessionResult).toEqual(sessionUser)
  })`
1 Like

@Sarah_62204, you are breaking forum’s policies by providing code that are answers to labs. Give a man a fish and you feed him for the day teach a man to fish and you feed him for the rest of his life.

Sorry, I will remove my comment

Thank you Sarah for answering. I am still stuck.

I had already implemented the getUserSession() function before I posted to the forum as follows:

  static async getUserSession(email) {
try {
  // TODO Ticket: User Management
  // Retrieve the session document corresponding with the user's email.
  return sessions.findOne({ email: email })
} catch (e) {
  console.error(`Error occurred while retrieving user session, ${e}`)
  return null
}
  }

I have a couple more hours left before the submission window is closed. I really need help.

Hi Anthony,

In your getUserSession() the query you are passing to findOne needs to be slightly modified.HINT:
the value is correct but you need to amend the key. If you look in Atlas, the sessions model doesn’t have a key “email” but instead has a “user_id” field.

3 Likes

Hello Sarah.
You have really gone out of your way to help me. I really really appreciate. Thank you.

I did not complete the ticket. Time ran out on my end.
Here is what I had done:

This was my getUsers() implementation.

  static async addUser(userInfo) {
/**
Ticket: Durable Writes

Please increase the durability of this method by using a non-default write
concern with ``insertOne``.
*/

try {
  // TODO Ticket: User Management
  // Insert a user with the "name", "email", and "password" fields.
  let { name, email, password } = userInfo;
  console.log(`${name}, ${email}, ${password}`)
  await users.insertOne(
    {
      name: name,
      email: email,
      password: password
    })

  // TODO Ticket: Durable Writes
  // Use a more durable Write Concern for this operation.
  // await users.insertOne({ someField: "someValue" })
  return { success: true }
} catch (e) {
  if (String(e).startsWith("MongoError: E11000 duplicate key error")) {
    return { error: "A user with the given email already exists." }
  }
  console.error(`Error occurred while adding new user, ${e}.`)
  return { error: e }
}

}

My loginUser() function:

  static async loginUser(email, jwt) {
try {
  // TODO Ticket: User Management
  // Use an UPSERT statement to update the "jwt" field in the document,
  // matching the "user_id" field with the email passed to this function.
  await sessions.updateOne(
    { user_id: email },
    { $set: { jwt: jwt } },
    { upsert: true },
  )
} catch (e) {
  console.error(`Error occurred while logging in user, ${e}`)
  return { error: e }
}

}

This was my logoutUser() function.

  static async logoutUser(email) {
try {
  // TODO Ticket: User Management
  // Delete the document in the `sessions` collection matching the email.
  await sessions.deleteOne({ user_id: email })
  return { success: true }
} catch (e) {
  console.error(`Error occurred while logging out user, ${e}`)
  return { error: e }
}

}

Finally, this was my getUserSession()

  static async getUserSession(email) {
try {
  // TODO Ticket: User Management
  // Retrieve the session document corresponding with the user's email.
  return sessions.findOne({ user_id: email })
} catch (e) {
  console.error(`Error occurred while retrieving user session, ${e}`)
  return null
}

}

The above implementations still kept failing with the following log:
`anthony@KYRA:~/Documents/mflix-js$ npm test -t user-management

server@1.0.0 test /home/anthony/Documents/mflix-js
jest --passWithNoTests “user-management”

Determining test suites to run…Setup Mongo Connection
(node:30357) 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.log src/dao/usersDAO.js:62
Magical Mr. Mistoffelees, magicz@cats.com, somehashedpw

console.log src/dao/usersDAO.js:62
Magical Mr. Mistoffelees, magicz@cats.com, somehashedpw

FAIL test/user-management.test.js (7.301s)
User Management
✓ it can add a new user to the database (698ms)
✓ it returns an error when trying to register duplicate user (295ms)
✕ it allows a user to login (303ms)
✓ it allows a user to logout (597ms)

● User Management › it allows a user to login

TypeError: Cannot read property 'success' of undefined

  48 |   test("it allows a user to login", async () => {
  49 |     const actual = await UsersDAO.loginUser(testUser.email, sessionUser.jwt)
> 50 |     expect(actual.success).toBeTruthy()
     |                   ^
  51 |     const sessionResult = await UsersDAO.getUserSession(testUser.email)
  52 |     delete sessionResult._id
  53 |     expect(sessionResult).toEqual(sessionUser)

  at success (test/user-management.test.js:50:19)
  at tryCatch (node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:62:40)
  at Generator.invoke [as _invoke] (node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:296:22)
  at Generator.prototype.(anonymous function) [as next] (node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:114:21)
  at step (node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
  at node_modules/babel-runtime/helpers/asyncToGenerator.js:28:13

Test Suites: 1 failed, 1 total
Tests: 1 failed, 3 passed, 4 total
Snapshots: 0 total
Time: 7.851s
Ran all test suites matching /user-management/i.
Teardown Mongo Connection
npm ERR! Test failed. See above for more details.`

As per the MongoDB university course, I failed the chapter because I could not submit the tickets in time. However, my main aim was to learn.

I still would like to know why the above failed. I could still be missing something, but I tried as much as I could to follow all the suggestions that were kindly offered to me on the forum.

I appreciate all you have done to my aid. Thank you for everything Sarah,
Anthony.

It looks like your loginUser() is not returning anything.

The error you have shown :

TypeError … of undefined means your function is not returning an object.

Cannot read property ‘success’ means the code expect an object with a property named ‘success’.

1 Like

Hi @Anthony_73816,

Please follow what @steevej-1495 has said. :slight_smile: Let me know if it doesn’t work out.

Kanika

Hello Kanika,
I managed to add a return success and it worked.
But I had to unregister from the course. I was time barred for the ticket submission.

I will join the next session of M220JS.

Thanks.

Sure @Anthony_73816! :slight_smile:

Kanika