Bird
Raised Fist0
Expressframework~20 mins

CRUD operations with Sequelize in Express - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Sequelize CRUD Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this Sequelize create operation?
Consider this Express route using Sequelize to create a new user. What will be the JSON response after a successful creation?
Express
app.post('/users', async (req, res) => {
  try {
    const user = await User.create({ name: 'Alice', age: 30 });
    res.json(user);
  } catch (error) {
    res.status(500).json({ error: 'Failed to create user' });
  }
});
A{"name": "Alice", "age": 30}
B{"error": "Failed to create user"}
Cnull
D{"id": 1, "name": "Alice", "age": 30, "createdAt": "<date>", "updatedAt": "<date>"}
Attempts:
2 left
💡 Hint
Sequelize returns the full created instance including auto-generated fields.
state_output
intermediate
2:00remaining
What is the result of this Sequelize update operation?
Given this code snippet updating a user's age, what will be the value of updatedUser.age after the operation?
Express
const updatedUser = await User.update({ age: 35 }, { where: { name: 'Alice' }, returning: true, plain: true });
console.log(updatedUser.age);
A35
Bundefined
C30
Dnull
Attempts:
2 left
💡 Hint
The returning: true option returns the updated instance.
🔧 Debug
advanced
2:00remaining
Why does this Sequelize delete operation fail with an error?
This code attempts to delete a user but throws an error. What is the cause?
Express
app.delete('/users/:id', async (req, res) => {
  try {
    await User.destroy({ id: req.params.id });
    res.json({ message: 'User deleted' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});
AThe 'where' clause is missing in the destroy method.
BThe 'id' parameter is not converted to a number.
CThe route method should be 'post' instead of 'delete'.
DThe destroy method does not exist in Sequelize.
Attempts:
2 left
💡 Hint
Sequelize's destroy method requires a 'where' object to specify which records to delete.
📝 Syntax
advanced
2:00remaining
Which option correctly retrieves all users older than 25 using Sequelize?
Select the correct Sequelize query to find all users with age greater than 25.
AUser.findAll({ where: { age: { [Op.gt]: 25 } } })
BUser.findAll({ where: { age: { $gt: 25 } } })
CUser.findAll({ where: { age: '>25' } })
DUser.findAll({ age: { gt: 25 } })
Attempts:
2 left
💡 Hint
Sequelize uses the Op object for operators like greater than.
🧠 Conceptual
expert
2:00remaining
What happens if you call Sequelize's update method without the 'where' option?
Consider this code: await User.update({ age: 40 }); What will be the result?
ASequelize throws a runtime error about missing 'where' clause.
BNo records will be updated because 'where' is missing.
CAll user records in the database will have their age set to 40.
DOnly the first user record will be updated.
Attempts:
2 left
💡 Hint
Without a 'where' clause, Sequelize updates all rows by default.

Practice

(1/5)
1. Which Sequelize method is used to add a new record to the database?
easy
A. update()
B. findAll()
C. create()
D. destroy()

Solution

  1. Step 1: Understand CRUD operations

    CRUD stands for Create, Read, Update, Delete. Each operation has a matching Sequelize method.
  2. Step 2: Match method to Create operation

    The create() method is used to add new records to the database.
  3. Final Answer:

    create() -> Option C
  4. Quick Check:

    Create = create() [OK]
Hint: Create means add new, so use create() method [OK]
Common Mistakes:
  • Confusing create() with findAll() which reads data
  • Using update() to add new records
  • Using destroy() which deletes records
2. Which of the following is the correct syntax to update a user's name to 'Alice' where id is 5 using Sequelize?
easy
A. User.update({ name: 'Alice' }, { where: { id: 5 } })
B. User.update({ where: { id: 5 } }, { name: 'Alice' })
C. User.update('Alice', { id: 5 })
D. User.update({ id: 5 }, { name: 'Alice' })

Solution

  1. Step 1: Recall Sequelize update syntax

    The update method takes two arguments: the new values object, and the options object with a where clause.
  2. Step 2: Match correct argument order and structure

    User.update({ name: 'Alice' }, { where: { id: 5 } }) correctly places the new values first and the where condition second.
  3. Final Answer:

    User.update({ name: 'Alice' }, { where: { id: 5 } }) -> Option A
  4. Quick Check:

    update(values, { where }) = User.update({ name: 'Alice' }, { where: { id: 5 } }) [OK]
Hint: Update needs values first, then where condition [OK]
Common Mistakes:
  • Swapping the order of arguments
  • Passing values inside where instead of separate object
  • Using strings instead of objects for values
3. Given the code:
const users = await User.findAll({ where: { age: { [Op.gt]: 18 } } });
console.log(users.length);

What will console.log(users.length) output?
medium
A. The total number of users in the database
B. An error because Op.gt is not defined
C. Always 0 because findAll returns undefined
D. The number of users older than 18

Solution

  1. Step 1: Understand findAll with where clause

    The findAll method returns all records matching the where condition. Here, it filters users with age greater than 18.
  2. Step 2: Determine what users.length represents

    users is an array of matching records, so users.length is the count of users older than 18.
  3. Final Answer:

    The number of users older than 18 -> Option D
  4. Quick Check:

    findAll with condition returns matching array length [OK]
Hint: findAll returns array; length counts matching records [OK]
Common Mistakes:
  • Thinking findAll returns undefined or null
  • Ignoring the where condition filtering
  • Assuming Op.gt is undefined without importing
4. What is wrong with this code snippet for deleting a user by id?
await User.destroy(id);
medium
A. destroy requires an object with a where clause, not just id
B. destroy cannot be awaited
C. destroy only works with arrays, not single values
D. destroy needs a callback function

Solution

  1. Step 1: Recall destroy method signature

    Sequelize's destroy method expects an options object with a where property to specify which records to delete.
  2. Step 2: Identify incorrect argument usage

    Passing just the id directly is incorrect; it must be inside { where: { id: id } }.
  3. Final Answer:

    destroy requires an object with a where clause, not just id -> Option A
  4. Quick Check:

    destroy({ where: { id } }) is correct [OK]
Hint: destroy needs where inside an object, not just id [OK]
Common Mistakes:
  • Passing id directly instead of inside where
  • Not awaiting asynchronous destroy call
  • Expecting destroy to accept callback
5. You want to update multiple users' status to 'active' where their last login was before 2023-01-01. Which Sequelize code correctly does this?
hard
A. User.update({ where: { lastLogin: { [Op.lt]: '2023-01-01' } } }, { status: 'active' })
B. User.update({ status: 'active' }, { where: { lastLogin: { [Op.lt]: new Date('2023-01-01') } } })
C. User.update('active', { lastLogin: { [Op.lt]: new Date('2023-01-01') } })
D. User.update({ status: 'active' }, { lastLogin: { [Op.lt]: new Date('2023-01-01') } })

Solution

  1. Step 1: Understand update method parameters

    The first argument is the values to update, the second is an options object with a where clause to filter records.
  2. Step 2: Check correct use of Op.lt and date object

    User.update({ status: 'active' }, { where: { lastLogin: { [Op.lt]: new Date('2023-01-01') } } }) correctly uses [Op.lt] with a Date object inside the where clause.
  3. Step 3: Verify argument order and structure

    The other options have incorrect argument order or missing where wrapper.
  4. Final Answer:

    User.update({ status: 'active' }, { where: { lastLogin: { [Op.lt]: new Date('2023-01-01') } } }) -> Option B
  5. Quick Check:

    update(values, { where: condition }) with Op.lt date [OK]
Hint: Update needs values first, then where with Op.lt date [OK]
Common Mistakes:
  • Swapping values and where arguments
  • Using string instead of Date object for date comparison
  • Omitting where wrapper around condition