User Preferences: preferences weren't saved correctly

Hello

Chapter 3, Ticket: User-Preferences
My solution passed all tests, but status test failed.
Message: “User Preferences weren’t saved correctly.”
I spent much much time on problem fixing. Still no clou at all. I need help!
Thank you!

/**

  • Given a user’s email and an object of new preferences, update that user’s
  • data to include those preferences.
  • @param {string} email - The email of the user to update.
  • @param {Object} preferences - The preferences to include in the user’s data.
  • @returns {DAOResponse}
    */
    static async updatePreferences(email, preferences) {
try {
  /**
  Ticket: User Preferences

  Update the "preferences" field in the corresponding user's document to
  reflect the new information in preferences.
  */

  preferences = preferences || {}

  // TODO Ticket: User Preferences
  // Use the data in "preferences" to update the user's preferences.

  const updateResponse = await users.updateOne(
    { user_id: email },
    { $set: { email, preferences } },
    { upsert: true }
  )
  if (updateResponse.matchedCount === 0) {
    return { error: "No user found with that email" }
  }
  return updateResponse
} catch (e) {
  console.error(
    `An error occurred while updating this user's preferences, ${e}`,
  )
  return { error: e }
}

}
MongoDB/Mongo_University_M220/mflix-js

jest --passWithNoTests “user-preferences”

Determining test suites to run…Setup Mongo Connection
PASS test/user-preferences.test.js
User Preferences
✓ Invalid user should not have preferences (271ms)
✓ Null preferences should be valid (133ms)
✓ Valid preferences are reflected in DB (459ms)

Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 2.107s, estimated 3s
Ran all test suites matching /user-preferences/i.
Teardown Mongo Connection

/**
Ticket: User Management

For this ticket, you will need to implement the following five methods:

  • getUser
  • addUser
  • loginUser
  • logoutUser
  • getUserSession

You can find these methods below this comment. Make sure to read the comments
in each method to better understand the implementation.

The method deleteUser is already given to you.
*/

/**

  • Finds a user in the users collection
  • @param {string} email - The email of the desired user
  • @returns {Object | null} Returns either a single user or nothing
    */
    static async getUser(email) {
    // TODO Ticket: User Management
    // Retrieve the user document corresponding with the user’s email.
    return await users.findOne({ email: email })
    }

/**

  • Adds a user to the users collection
  • @param {UserInfo} userInfo - The information of the user to add
  • @returns {DAOResponse} Returns either a “success” or an “error” Object
    /
    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.
  // TODO Ticket: Durable Writes
  // Use a more durable Write Concern for this operation.
 /* await users.insertOne({ name: userInfo.name, 
                          email: userInfo.email,
                          password: userInfo.password
                        })*/
                        await users.insertOne({...userInfo})
  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 }
}

}

/**

  • Adds a user to the sessions collection

  • @param {string} email - The email of the user to login

  • @param {string} jwt - A JSON web token representing the user’s claims

  • @returns {DAOResponse} Returns either a “success” or an “error” Object
    */
    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 }

    )
    return { success: true }
    } catch (e) {
    console.error(Error occurred while logging in user, ${e})
    return { error: e }
    }
    }

/**

  • Removes a user from the sessions collection
  • @param {string} email - The email of the user to logout
  • @returns {DAOResponse} Returns either a “success” or an “error” Object
    */
    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 }
    }
    }

/**

  • Gets a user from the sessions collection
  • @param {string} email - The email of the user to search for in sessions
  • @returns {Object | null} Returns a user session Object, an “error” Object
  • if something went wrong, or null if user was not found.
    */
    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
    }
    }

/**

  • Removes a user from the sessions and users collections
  • @param {string} email - The email of the user to delete
  • @returns {DAOResponse} Returns either a “success” or an “error” Object
    */
    static async deleteUser(email) {
    try {
    await users.deleteOne({ email })
    await sessions.deleteOne({ user_id: email })
    if (!(await this.getUser(email)) && !(await this.getUserSession(email))) {
    return { success: true }
    } else {
    console.error(Deletion unsuccessful)
    return { error: Deletion unsuccessful }
    }
    } catch (e) {
    console.error(Error occurred while deleting user, ${e})
    return { error: e }
    }
    }

/**

  • Given a user’s email and an object of new preferences, update that user’s
  • data to include those preferences.
  • @param {string} email - The email of the user to update.
  • @param {Object} preferences - The preferences to include in the user’s data.
  • @returns {DAOResponse}
    */
    static async updatePreferences(email, preferences) {
try {
  /**
  Ticket: User Preferences

  Update the "preferences" field in the corresponding user's document to
  reflect the new information in preferences.
  */

  preferences = preferences || {}

  // TODO Ticket: User Preferences
  // Use the data in "preferences" to update the user's preferences.

  const updateResponse = await users.updateOne(
    { user_id: email },
    { $set: { email, preferences } },
    { upsert: true }
  )
  if (updateResponse.matchedCount === 0) {
    return { error: "No user found with that email" }
  }
  return updateResponse
} catch (e) {
  console.error(
    `An error occurred while updating this user's preferences, ${e}`,
  )
  return { error: e }
}

}

static async checkAdmin(email) {
try {
const { isAdmin } = await this.getUser(email)
return isAdmin || false
} catch (e) {
return { error: e }
}
}

static async makeAdmin(email) {
try {
const updateResponse = users.updateOne(
{ email },
{ $set: { isAdmin: true } },
)
return updateResponse
} catch (e) {
return { error: e }
}
}
}

/**

  • Parameter passed to addUser method
  • @typedef UserInfo
  • @property {string} name
  • @property {string} email
  • @property {string} password
    */

/**

  • Success/Error return object
  • @typedef DAOResponse
  • @property {boolean} [success] - Success
  • @property {string} [error] - Error
    */

Update the “preferences” field in the corresponding user’s document to
reflect the new information in preferences.
So, the HINT in $set

Hello Valerii

Thank you Very much!
I was in the tunnel with the user_id … ;-(
Now I got it fixed :slight_smile:

You are welcome
:grinning:

Hi @Valerii_13861. Could you please provide a bit more hints to this issue. I have been struggling with it for a while!

Thanks !:slight_smile:

I think from the time this Q asked the test message change to:

Valid preferences are reflected in DB

under user-preferences.test.

updateOne defenition

db.collection.updateOne(filter, update, options)
  • filter (Set query selectors to return user by email (one docoument).
  • update: modifications this document

Examples: https://docs.mongodb.com/manual/reference/method/db.collection.updateOne/#examples

1 Like