Bird
Raised Fist0
Expressframework~20 mins

Defining 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
🎖️
Express Model 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 Express model definition code?
Consider this Express model definition using Mongoose. What will be the output when trying to create a new user without the required 'email' field?
Express
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: String,
  email: { type: String, required: true },
  age: Number
});

const User = mongoose.model('User', userSchema);

async function createUser() {
  try {
    const user = new User({ name: 'Alice', age: 30 });
    await user.save();
    console.log('User saved');
  } catch (error) {
    console.log(error.message);
  }
}

createUser();
AUser saved
BTypeError: Cannot read property 'save' of undefined
CValidation failed: email: Path `email` is required.
DSyntaxError: Unexpected token
Attempts:
2 left
💡 Hint
Think about what happens when a required field is missing in a Mongoose model.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a Mongoose model with a nested schema?
You want to define a Mongoose model for a blog post that includes a nested 'author' object with 'name' and 'email'. Which code correctly defines this model?
A
const postSchema = new mongoose.Schema({
  title: String,
  author: {
    name: String,
    email: String
  }
});
const Post = mongoose.model('Post', postSchema);
B
const postSchema = new mongoose.Schema({
  title: String,
  author: String
});
const Post = mongoose.model('Post', postSchema);
C
const postSchema = new mongoose.Schema({
  title: String,
  author: [
    { name: String, email: String }
  ]
});
const Post = mongoose.model('Post', postSchema);
D
const authorSchema = new mongoose.Schema({
  name: String,
  email: String
});
const postSchema = new mongoose.Schema({
  title: String,
  author: authorSchema
});
const Post = mongoose.model('Post', postSchema);
Attempts:
2 left
💡 Hint
Nested schemas should be defined separately and referenced inside the main schema.
🔧 Debug
advanced
2:00remaining
Why does this Mongoose model throw a 'Missing schema' error?
Examine the code below. Why does it throw an error 'Missing schema for model "User"' when trying to create a new User?
Express
const mongoose = require('mongoose');

const User = mongoose.model('User');

async function createUser() {
  const user = new User({ name: 'Bob', email: 'bob@example.com' });
  await user.save();
  console.log('User saved');
}

createUser();
ABecause the model name 'User' is reserved and cannot be used
BBecause the schema was not defined before calling mongoose.model('User')
CBecause the 'new' keyword is missing when creating the User instance
DBecause mongoose.connect() was not called before defining the model
Attempts:
2 left
💡 Hint
Check if the schema is passed when defining the model.
state_output
advanced
2:00remaining
What is the value of 'user.isActive' after saving this Mongoose model?
Given this schema with a default value, what will be the value of 'isActive' for a new user saved without specifying it?
Express
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: String,
  isActive: { type: Boolean, default: true }
});

const User = mongoose.model('User', userSchema);

async function createUser() {
  const user = new User({ name: 'Carol' });
  await user.save();
  console.log(user.isActive);
}

createUser();
Atrue
Bfalse
Cundefined
Dnull
Attempts:
2 left
💡 Hint
Look at the default value set in the schema for 'isActive'.
🧠 Conceptual
expert
2:00remaining
Which statement about Mongoose schema options is correct?
Consider these statements about Mongoose schema options. Which one is true?
ASetting 'timestamps: true' in schema options automatically adds 'createdAt' and 'updatedAt' fields and updates them on save.
BThe 'strict' option set to false means Mongoose will throw an error if extra fields are added to documents.
CUsing 'versionKey: false' disables all validation rules on the schema.
DThe 'toJSON' option cannot be customized in a Mongoose schema.
Attempts:
2 left
💡 Hint
Think about what 'timestamps' option does in Mongoose.

Practice

(1/5)
1. What is the main purpose of defining a model in an Express app using Mongoose?
easy
A. To style the app with CSS
B. To define the structure and rules for data stored in the database
C. To handle HTTP requests and responses
D. To create the user interface of the app

Solution

  1. Step 1: Understand what a model represents

    A model defines how data is structured and validated in the database.
  2. Step 2: Identify the role of models in Express apps

    Models help manage data and enforce rules before saving to the database.
  3. Final Answer:

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

    Model = Data structure and rules [OK]
Hint: Models define data shape and rules, not UI or styling [OK]
Common Mistakes:
  • Confusing models with UI components
  • Thinking models handle HTTP requests
  • Assuming models style the app
2. Which of the following is the correct way to define a Mongoose model named Book with a schema having a title field of type String?
easy
A. const Book = mongoose.model('Book', new mongoose.Schema({ title: String }));
B. const Book = mongoose.schema('Book', { title: String });
C. const Book = mongoose.model('Book', { title: String });
D. const Book = new mongoose.model('Book', { title: String });

Solution

  1. Step 1: Recall Mongoose model syntax

    Mongoose models require a schema object created with new mongoose.Schema().
  2. Step 2: Check each option for correct usage

    const Book = mongoose.model('Book', new mongoose.Schema({ title: String })); correctly uses mongoose.model('Book', new mongoose.Schema({ title: String })). Others misuse schema or omit new mongoose.Schema().
  3. Final Answer:

    const Book = mongoose.model('Book', new mongoose.Schema({ title: String })); -> Option A
  4. Quick Check:

    Model needs new Schema() [OK]
Hint: Use new mongoose.Schema() inside mongoose.model() [OK]
Common Mistakes:
  • Using mongoose.schema instead of new Schema()
  • Passing plain object instead of Schema instance
  • Using new keyword incorrectly with mongoose.model
3. Given the following code, what will console.log(book.title) output?
const mongoose = require('mongoose');
const { Schema } = mongoose;

const bookSchema = new Schema({ title: String });
const Book = mongoose.model('Book', bookSchema);

const book = new Book({ title: 'Express Guide' });
console.log(book.title);
medium
A. Error: book.title is not defined
B. undefined
C. 'Express Guide'
D. null

Solution

  1. Step 1: Understand model instance creation

    Creating new Book({ title: 'Express Guide' }) sets the title property on the instance.
  2. Step 2: Access the title property

    Logging book.title outputs the string 'Express Guide' as assigned.
  3. Final Answer:

    'Express Guide' -> Option C
  4. Quick Check:

    Instance property = 'Express Guide' [OK]
Hint: Instance properties match schema fields given at creation [OK]
Common Mistakes:
  • Expecting undefined because of missing database save
  • Confusing model with schema
  • Thinking title is a method, not a property
4. Identify the error in this model definition code:
const mongoose = require('mongoose');
const bookSchema = mongoose.Schema({ title: String });
const Book = mongoose.model('Book', bookSchema);

const book = new Book({ title: 123 });
medium
A. Schema should be created with new Schema(), not mongoose.Schema()
B. Missing call to connect to the database before defining model
C. Model name 'Book' must be lowercase
D. The title field value should be a string, not a number

Solution

  1. Step 1: Check schema field types and values

    The schema defines title as a String, but the instance is created with a number 123.
  2. Step 2: Identify type mismatch error

    Mongoose expects a string for title, so passing a number is a validation error.
  3. Final Answer:

    The title field value should be a string, not a number -> Option D
  4. Quick Check:

    Schema type mismatch causes error [OK]
Hint: Match data types in schema and instance exactly [OK]
Common Mistakes:
  • Ignoring type mismatch errors
  • Thinking model names must be lowercase
  • Confusing schema creation syntax
5. You want to define a Mongoose model User with fields name (string), age (number), and email (string, required). Which code correctly defines this model with validation?
hard
A. const userSchema = new mongoose.Schema({ name: String, age: Number, email: { type: String, required: true } }); const User = mongoose.model('User', userSchema);
B. const userSchema = new Schema({ name: String, age: Number, email: String, required: true }); const User = mongoose.model('User', userSchema);
C. const userSchema = new Schema({ name: String, age: Number, email: String }); const User = mongoose.model('User', userSchema, { required: ['email'] });
D. const userSchema = new Schema({ name: String, age: Number, email: { type: String } }); const User = mongoose.model('User', userSchema);

Solution

  1. Step 1: Understand how to set required fields in schema

    Required fields must be defined inside the field object with required: true.
  2. Step 2: Check each option for correct required syntax

    const userSchema = new mongoose.Schema({ name: String, age: Number, email: { type: String, required: true } }); const User = mongoose.model('User', userSchema); correctly sets email: { type: String, required: true }. Others either place required outside the field or omit it.
  3. Final Answer:

    const userSchema = new mongoose.Schema({ name: String, age: Number, email: { type: String, required: true } }); const User = mongoose.model('User', userSchema); -> Option A
  4. Quick Check:

    Required fields inside field object [OK]
Hint: Put required: true inside the field's object definition [OK]
Common Mistakes:
  • Placing required outside the field object
  • Omitting required for mandatory fields
  • Misusing model options for validation