CodingNic

Mongoose: Schemas and Models

Exercises

Mongoose: Schemas and Models 25 min read

Exercises

Objectives

By the end of this lesson, you should be able to:

  • Define a Mongoose schema with multiple validation rules
  • Connect a model to a real MongoDB database and perform CRUD through it
  • Confirm invalid data is rejected before it reaches the database

⚠️ A note on verification: the validation section of this exercise runs entirely inside Node.js, no database connection needed, and was actually run. Connecting and performing CRUD against a real MongoDB server follows Mongoose’s stable, documented behavior, and should be run on your own machine, following Lesson 2’s connection setup.

Exercise: A Product Catalog

a) Define the schema.

javascript
const productSchema = new mongoose.Schema({
  name: { type: String, required: true },
  price: { type: Number, required: true, min: 0 },
  sku: { type: String, required: true, match: /^[A-Z]{3}-\d{4}$/ }
});

const Product = mongoose.model('Product', productSchema);

b) Validate a correct document.

javascript
const valid = new Product({ name: 'Keyboard', price: 49.99, sku: 'KEY-1001' });
await valid.validate();
console.log('Valid, no errors');
text
Valid, no errors

c) Validate a negative price.

javascript
const negativePrice = new Product({ name: 'Mouse', price: -5, sku: 'MOU-1002' });
try {
  await negativePrice.validate();
} catch (err) {
  console.log(err.errors.price.message);
}
text
Path `price` (-5) is less than minimum allowed value (0).

d) Validate a badly formatted SKU.

javascript
const badSku = new Product({ name: 'Monitor', price: 199, sku: 'bad-sku' });
try {
  await badSku.validate();
} catch (err) {
  console.log(err.errors.sku.message);
}
text
Path `sku` is invalid (bad-sku).

e) Connect and save. Connect Mongoose to a real MongoDB database (following Lesson 2), and use Product.create() to save the valid product from part (b). Confirm it appears when queried with Product.find().

f) Attempt to save invalid data. Try Product.create() with the negative-price product from part (c), and confirm it’s rejected with the same validation error, before ever reaching the database.

g) Add a fourth rule. Add an inStock field (Boolean, default: true), and a description field limited to 500 characters using Mongoose’s maxlength option. Validate a document exceeding that limit, and confirm the error message.

Recap

This module covered defining Mongoose schemas with field types and validation rules, turning a schema into a connected model, and confirming, with real, executed validation logic, that invalid data is rejected before it ever reaches the database.

Next module: modeling relationships between MongoDB documents, embedding versus referencing, and when to choose each.