A First Schema
A schema is a plan that describes the shape of a document. It names each field and its type.
The schema
This schema gives a note a title and a done flag.
const noteSchema = new mongoose.Schema({
title: String,
done: Boolean
});The model
This line builds the Note model from the schema.
const Note = mongoose.model('Note', noteSchema);The title type
This line prints the type of the title field.
console.log(Note.schema.path('title').instance);Example
import mongoose from 'mongoose';
await mongoose.connect('mongodb://localhost:27017/notes');
const noteSchema = new mongoose.Schema({
title: String,
done: Boolean
});
const Note = mongoose.model('Note', noteSchema);
console.log(Note.modelName);
console.log(Note.schema.path('title').instance);
console.log(Note.schema.path('done').instance);
await mongoose.disconnect();Key points
- A schema lists the fields a document may hold.
- Each field has a type, such as String or Boolean.
- A model is built from a schema, and it works with one collection.
- The model name is Note, and the collection holds notes.
- Mongoose adds an _id field to every document.
In this example, the connect line opens the link to the notes database. The schema gives a note a title and a done flag. The model line builds the Note model from the schema. The prints show the model name and the two field types. The disconnect line closes the link.
Note
The schema does not save anything. It only describes the shape.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does a schema describe?