Share
Explore

MONGO and MONGOOSE Lab Workbook

Learning Outcomes:

Use Node.js and MONGOOSE to make and populate data into a MONGO database.
Theme the examples on Pokemon for collections and documents.

Introduction

Welcome to the Node.js and Mongoose lab workbook! In this workbook, you will learn how to use Node.js and Mongoose to make and populate data into a MongoDB database. We will be using Pokemon as our theme for collections and documents.

Prerequisites

Before we get started, make sure you have the following installed on your machine:
Postman

Setting up the Project

Create a new directory for your project and navigate to it in your terminal. (Wednesday Lab Test 1)
Initialize a new Node.js project by running npm init -y.
Install the necessary dependencies by running npm install express mongoose.
Create a new file called server.js and add the following code:

const express = require("express");const mongoose = require("mongoose");const app = express();
mongoose .connect("mongodb://localhost/pokemon", { useNewUrlParser: true }) .then(() => console.log("MongoDB Connected")) .catch((err) => console.log(err));
app.listen(3000, () => console.log("Server listening on port 3000"));

This mongo code sets up a basic Express server and connects to a MongoDB database named "pokemon".

Creating a Model

Create a new file called pokemon.js in a directory called models.
Add the following code:

Lecture Notes: Mongoose Schemas

In MongoDB, data is stored in collections.
A collection is a group of documents, which are JSON-like objects that contain data.
Mongoose is an Object Data Modeling (ODM) library for MongoDB and provides Node.js APIs to define schemas to model the data in collections.

What is a Schema?

A schema is a blueprint for a collection. It defines the structure of the documents in the collection, including the field names, types, and any validation constraints.
In Mongoose, a schema is defined as a JavaScript object with key-value pairs that represent the fields in the collection.
const mongoose = require('mongoose');
const pokemonSchema = new mongoose.Schema({ name: { type: String, required: true }, type: { type: String, required: true }, level: { type: Number, required: true }});
In this example, we define a schema for a Pokemon collection, which has three fields: name, type, and level. The type key specifies the data type of the field, and the required key specifies whether the field is required.

How are Schemas Used?

Once a schema is defined, it can be used to create a model.
A model is a JavaScript class that represents a collection and provides an interface for interacting with the data in the collection. To create a model, we pass the schema to the mongoose.model() method.
const Pokemon = mongoose.model('Pokemon', pokemonSchema);

CRUD:

In this example, we create a model for the Pokemon collection using the pokemonSchema. Now we can use the Pokemon model to perform operations on the collection, such as creating, reading, updating, and deleting documents.
const pokemon = new Pokemon({ name: 'Pikachu', type: 'Electric', level: 10});pokemon.save();
In this example, we create a new document in the Pokemon collection using the Pokemon model.
We pass an object with the field values to the Pokemon constructor, and then call the save() method to save the document to the collection.

Why are Schemas Used?

Schemas provide a way to enforce data consistency and validation when working with MongoDB.
By defining a schema, we can ensure that all documents in a collection have the same structure and that fields have the correct data types and validation constraints.
This helps to prevent errors and ensure that the data is consistent and accurate.
In addition, schemas provide a way to define methods and statics on models.
Methods are functions that operate on individual documents, while statics are functions that operate on the entire collection.
These methods and statics can be used to perform complex operations on the data in the collection and provide a more powerful interface for working with MongoDB.
In conclusion, Mongoose schemas are a powerful tool for modeling data in MongoDB collections.
They provide a way to enforce data consistency and validation, define methods and statics on models, and provide a powerful interface for working with MongoDB.
const mongoose = require('mongoose');
const pokemonSchema = new mongoose.Schema({ name: { type: String, required: true }, type: { type: String, required: true }, level: { type: Number, required: true }});
const Pokemon = mongoose.model('Pokemon', pokemonSchema);
(async () => { try { await mongoose.connect('mongodb://localhost:27017/pokemonDB', { useNewUrlParser: true, useUnifiedTopology: true, }); console.log('Connected to database!');
const pokemonData = [ { name: 'Pikachu', type: 'Electric', level: 10 }, { name: 'Charmander', type: 'Fire', level: 7 }, { name: 'Squirtle', type: 'Water', level: 5 } ]; await Pokemon.insertMany(pokemonData); console.log('Data inserted!'); } catch (error) { console.error(error); } finally { await mongoose.disconnect(); console.log('Disconnected from database!'); }})();

This code creates a Mongoose schema for Pokemon with three fields: name, type, and level.

Creating Routes

Create a new file called pokemon.js in a directory called routes.
Add the following code:
const express = require("express");const router = express.Router();const Pokemon = require("../models/pokemon");
router.get("/", async (req, res) => {
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.