Bird
Raised Fist0
Expressframework~20 mins

Defining schemas and models 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
🎖️
Schema Mastery Badge
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 Mongoose schema validation?
Consider this Mongoose schema for a User model. What happens if you try to save a user with an empty email field?
Express
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
  email: { type: String, required: true },
  name: String
});
const User = mongoose.model('User', userSchema);

const user = new User({ name: 'Alice' });
user.save().catch(err => console.log(err.message));
AIt throws a validation error because email is required
BIt saves but email is saved as an empty string
CIt throws a syntax error due to missing email
DIt saves successfully with email as undefined
Attempts:
2 left
💡 Hint
Check the 'required' property in the schema definition.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a Mongoose schema with a nested object?
You want to define a schema for a BlogPost with a nested author object containing name and age. Which code snippet is correct?
Aconst blogSchema = new mongoose.Schema({ title: String, author: { type: Object, name: String, age: Number } });
Bconst blogSchema = new mongoose.Schema({ title: String, author: mongoose.Schema({ name: String, age: Number }) });
Cconst blogSchema = new mongoose.Schema({ title: String, author: new mongoose.Schema({ name: String, age: Number }) });
Dconst blogSchema = new mongoose.Schema({ title: String, author: { name: String, age: Number } });
Attempts:
2 left
💡 Hint
Nested objects can be defined directly as plain objects inside the schema.
🔧 Debug
advanced
2:00remaining
Why does this Mongoose model throw a 'Missing schema' error?
You have this code snippet. Why does it throw an error when trying to create a model?
Express
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({ username: String });
const User = mongoose.model('User');
ABecause the schema is missing a required field
BBecause the model is created without passing the schema as the second argument
CBecause mongoose.Schema is not a function
DBecause the model name 'User' is reserved
Attempts:
2 left
💡 Hint
Check the parameters passed to mongoose.model.
state_output
advanced
2:00remaining
What is the value of 'user.isNew' after saving a new document?
Given this code, what will be the value of 'user.isNew' after calling save() successfully?
Express
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({ name: String });
const User = mongoose.model('User', userSchema);

async function run() {
  const user = new User({ name: 'Bob' });
  console.log(user.isNew);
  await user.save();
  console.log(user.isNew);
}
run();
Atrue before save, false after save
Bfalse before save, true after save
Ctrue both before and after save
Dfalse both before and after save
Attempts:
2 left
💡 Hint
Check the meaning of 'isNew' property in Mongoose documents.
🧠 Conceptual
expert
2:00remaining
Which option best describes the purpose of Mongoose middleware in schemas?
What is the main use of middleware functions in Mongoose schemas?
ATo define custom validation rules for schema fields
BTo automatically create indexes on schema fields
CTo run functions before or after certain schema methods like save or remove
DTo convert schema definitions into JSON objects
Attempts:
2 left
💡 Hint
Think about hooks that run during document lifecycle events.

Practice

(1/5)
1. What is the main purpose of defining a schema in an Express app using Mongoose?
easy
A. To specify the structure and rules for the data stored in the database
B. To create the server routes for handling requests
C. To style the frontend components
D. To manage user authentication sessions

Solution

  1. Step 1: Understand what a schema does

    A schema defines the shape and rules of data in the database, like what fields exist and their types.
  2. Step 2: Differentiate from other app parts

    Server routes handle requests, styling is frontend, and sessions manage users, none define data structure.
  3. Final Answer:

    To specify the structure and rules for the data stored in the database -> Option A
  4. Quick Check:

    Schema = data structure rules [OK]
Hint: Schemas define data shape and rules, not routes or styles [OK]
Common Mistakes:
  • Confusing schema with routing logic
  • Thinking schema handles frontend styling
  • Mixing schema with session management
2. Which of the following is the correct way to define a Mongoose schema for a user with a required name field of type String?
easy
A. const userSchema = new mongoose.Schema({ name: String, required: true });
B. const userSchema = new mongoose.Schema({ name: { type: String, required: true } });
C. const userSchema = mongoose.Schema({ name: String, required: true });
D. const userSchema = new Schema({ name: String, required: true });

Solution

  1. Step 1: Check correct schema syntax

    Mongoose schema requires fields as objects with type and options, e.g., { name: { type: String, required: true } }.
  2. Step 2: Identify errors in other options

    const userSchema = new mongoose.Schema({ name: String, required: true }); puts required outside the field object, C misses 'new' keyword, D misses 'mongoose.' prefix.
  3. Final Answer:

    const userSchema = new mongoose.Schema({ name: { type: String, required: true } }); -> Option B
  4. Quick Check:

    Field options go inside an object with type [OK]
Hint: Use { field: { type: Type, required: true } } syntax [OK]
Common Mistakes:
  • Placing 'required' outside the field object
  • Forgetting 'new' keyword before mongoose.Schema
  • Omitting 'mongoose.' prefix for Schema
3. Given the following code, what will be the output when creating a new user without the 'age' field?
const userSchema = new mongoose.Schema({ name: { type: String, required: true }, age: Number });
const User = mongoose.model('User', userSchema);
const newUser = new User({ name: 'Alice' });
console.log(newUser.age);
medium
A. 0
B. null
C. undefined
D. Throws an error because age is missing

Solution

  1. Step 1: Understand default values in schema

    Since 'age' is defined as Number but not required and no default is set, missing 'age' means its value is undefined.
  2. Step 2: Check behavior when logging missing field

    Logging newUser.age prints undefined, no error occurs because 'age' is optional.
  3. Final Answer:

    undefined -> Option C
  4. Quick Check:

    Optional fields without default = undefined [OK]
Hint: Missing optional fields default to undefined, not error [OK]
Common Mistakes:
  • Assuming missing number fields default to 0
  • Expecting null instead of undefined
  • Thinking missing optional fields cause errors
4. Identify the error in this schema definition:
const productSchema = new mongoose.Schema({
  title: { type: String, required: true },
  price: { type: Number, required: 'Price is required' }
});
medium
A. Missing comma after the title field definition
B. Price field type should be String, not Number
C. Schema must use 'new Schema' without 'mongoose.' prefix
D. The required field should be a boolean, not a string message

Solution

  1. Step 1: Check 'required' field usage

    In Mongoose, 'required' can be a boolean or an array with message, but a string alone is invalid.
  2. Step 2: Validate other syntax parts

    Commas are correct, 'mongoose.Schema' is valid, and price as Number is appropriate.
  3. Final Answer:

    The required field should be a boolean, not a string message -> Option D
  4. Quick Check:

    'required' must be boolean or [boolean, message] [OK]
Hint: Use true or [true, 'msg'] for required, not just string [OK]
Common Mistakes:
  • Using string alone for 'required' option
  • Confusing schema constructor syntax
  • Wrong data type for price field
5. You want to create a Mongoose model for a blog post with a title (required string), content (string), and tags (array of strings). Which schema definition correctly models this?
hard
A. const postSchema = new mongoose.Schema({ title: { type: String, required: true }, content: String, tags: [String] });
B. const postSchema = new mongoose.Schema({ title: String, required: true, content: String, tags: Array });
C. const postSchema = new mongoose.Schema({ title: { type: String }, content: String, tags: { type: [String], required: true } });
D. const postSchema = new mongoose.Schema({ title: { type: String, required: true }, content: String, tags: { type: String[] } });

Solution

  1. Step 1: Check required title field syntax

    const postSchema = new mongoose.Schema({ title: { type: String, required: true }, content: String, tags: [String] }); correctly sets title as { type: String, required: true }.
  2. Step 2: Verify tags as array of strings

    const postSchema = new mongoose.Schema({ title: { type: String, required: true }, content: String, tags: [String] }); uses tags: [String], which is the correct way to define an array of strings in Mongoose.
  3. Step 3: Identify errors in other options

    A uses invalid { type: String[] } syntax for tags; B places 'required' outside title field object and uses invalid tags: Array; C makes tags required incorrectly.
  4. Final Answer:

    const postSchema = new mongoose.Schema({ title: { type: String, required: true }, content: String, tags: [String] }); -> Option A
  5. Quick Check:

    Array of strings = [String], required inside field object [OK]
Hint: Use [String] for string arrays and required inside field object [OK]
Common Mistakes:
  • Placing 'required' outside field object
  • Using 'String[]' instead of [String]
  • Setting array type incorrectly