Define a Mongoose schema and model
schema syntax and the schema-to-model step.
new mongoose.Schema with field options (type, required, default), then mongoose.model('Product', schema) to get a model.
WHAT THIS TESTS This verifies you can define field-level structure and validation in a Mongoose schema and understand the distinct step of compiling it into a model.
A GOOD ANSWER COVERS A schema describes the shape and rules of documents. You create one with new mongoose.Schema and define each field; for fields needing options you use the object form, where type names the data type and other keys add validation or behavior. So name becomes { type: String, required: true }, making it a required string, and price becomes { type: Number, default: 0 }, a number that defaults to 0 when omitted. Once the schema is defined, you compile it into a model with mongoose.model('Product', productSchema). The model is the constructor and query interface you use to create, read, update, and delete documents; Mongoose also pluralizes and lowercases the model name to derive the collection name (products). The schema defines structure and validation; the model is how you interact with the data.
COMMON WRONG ANSWERS Confusing schema and model, or thinking they are the same thing. Using the shorthand name: String when you also need required, which has nowhere to put the option. Forgetting type inside the object form so the validator is misread. Expecting default to apply on updates rather than only on document creation when the field is absent.
LIKELY FOLLOW-UPS What collection name does Mongoose derive? How do you add custom validators or enums? What is the difference between required and default? How do timestamps work?
ONE CONCRETE EXAMPLE const productSchema = new mongoose.Schema({ name: { type: String, required: true }, price: { type: Number, default: 0 } }); const Product = mongoose.model('Product', productSchema); Now new Product({ name: 'Pen' }).save() persists a document with price defaulted to 0, while new Product({}).save() rejects because name is required, demonstrating both options in action.
Read the original → mongoosejs.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.