Your first database with Node
Start here. What a document, a schema and a model are, then save and read your first books.
New to databases? Good: this track starts from zero, and every lesson ends with code you run right here in the browser. No install, no cloud account.
Three words
| Word | Think of it as | Example |
|---|---|---|
| document | one record, shaped like a JS object | { title: "Dune", year: 1965 } |
| collection | a folder of similar documents | all the books |
| schema / model | the rules for a collection, and the tool to talk to it | "a book has a title, and it's required" |
MongoDB stores documents. Mongoose is the Node library that adds schemas on top and gives you a model with methods like create and find.
The whole loop in four lines
const bookSchema = new mongoose.Schema({ title: { type: String, required: true }, year: Number });
const Book = mongoose.model("Book", bookSchema);
await Book.create({ title: "Dune", year: 1965 }); // save
const books = await Book.find(); // read them all
Every database call is asynchronous: it returns a Promise, so you await it. Forgetting await is the number-one beginner bug: you get a Promise instead of your data.
What the schema gives you
- Types:
year: "2001"is converted to the number2001. - Validation: a missing required
titlemakescreatethrow, so bad data never lands. - Defaults: fields you leave out get a sensible value.
- An
_idon every document, created for you.
Your turn
Below are two exercises. Write the code, press Run, and watch the tests go green. Stuck? Open a hint; they get more specific one at a time.
Define your first model
Describe a Book to the database: a required title, an author that defaults to 'Unknown', and a numeric year.