Today, we're embarking on a journey into MongoDB. We'll be unveiling Schemas, Models, and Data Read Operations. In simpler terms, Schemas form the database structure, Models generate data, and Data Read Operations fetch it. So, let's go!
A Schema in MongoDB is akin to an architectural blueprint. In our analogy, it functions as the layout for organizing books in a library. A Schema consists of:
Let's create a Schema in which the fields represent different book categories.
JavaScript1const mongoose = require('mongoose'); 2const { Schema } = mongoose; 3 4const bookSchema = new Schema({ 5 title: String, 6 author: String, 7 isbn: Number 8}); 9 10module.exports = mongoose.model('Book', bookSchema);
We've generated a Book
Schema with title
, author
, and isbn
. MongoDB comes packed with built-in validation options to maintain data consistency.
We then export the bookSchema
, which other files can access via "Book".
A Model in MongoDB represents a schema — the individual books in our library, to be precise.
JavaScript1const mongoose = require('mongoose'); 2const Book = require('./bookSchema'); 3let newBook = new Book({ 4 title: "Eloquent JavaScript", 5 author: "Marijn Haverbeke", 6 isbn: 9781593279509 7});
We've created a Book
model, similar to placing a book on a library shelf.
We first import the bookSchema
via const Book = require('./bookSchema');
We can now create a new instance of Book
, that follows the requirements of
bookSchema
.
You may have noticed that initialDBSetup();
is called in the practices. This
function creates the schema and populates the collections of our database.
Reading data yields matches — much like finding a book in our library. MongoDB offers methods such as find()
and findOne()
for this purpose.
Let's fetch our books:
JavaScript1async function findBooksByAuthor(name) { 2 try { 3 return await Book.find({ author: name }); 4 } catch (err) { 5 console.error("Error finding book by author:", err); 6 } 7} 8 9async function findBookByTitle(title) { 10 try { 11 return await Book.findOne({ title: title }); 12 } catch (err) { 13 console.error("Error finding book by title:", err); 14 } 15}
The first function finds all the books written by the specified author. The second function locates the specific book by title.
Great job! You have learned about MongoDB's Schemas and Models and performed data read operations. Remember, Schemas constitute blueprints, Models represent data instances, and read operations equate to retrieving data. Now, let's proceed to some hands-on exercises to consolidate our knowledge. Happy coding!