Performance: Defining models
This affects server response time and initial page load speed by influencing how data is structured and retrieved.
Jump into concepts and practice - no test required
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: { type: String, required: true, index: true }, age: { type: Number, min: 0 }, addressId: { type: mongoose.Schema.Types.ObjectId, ref: 'Address' } }); module.exports = mongoose.model('User', userSchema);
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: String, age: Number, address: { street: String, city: String, zip: String } }); module.exports = mongoose.model('User', userSchema);
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Deeply nested schema without indexes | N/A (server-side) | N/A | N/A | [X] Bad |
| Schema with indexed fields and references | N/A (server-side) | N/A | N/A | [OK] Good |
Book with a schema having a title field of type String?new mongoose.Schema().mongoose.model('Book', new mongoose.Schema({ title: String })). Others misuse schema or omit new mongoose.Schema().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);new Book({ title: 'Express Guide' }) sets the title property on the instance.book.title outputs the string 'Express Guide' as assigned.const mongoose = require('mongoose');
const bookSchema = mongoose.Schema({ title: String });
const Book = mongoose.model('Book', bookSchema);
const book = new Book({ title: 123 });title as a String, but the instance is created with a number 123.title, so passing a number is a validation error.User with fields name (string), age (number), and email (string, required). Which code correctly defines this model with validation?required: true.email: { type: String, required: true }. Others either place required outside the field or omit it.