Working with Database
using Mongoose
WIF2003 WEB PROGRAMMING
Objectives
Introduction to Mongoose
Using a Mongo Database with Mongoose
Using MongoDB with Mongoose in an Express
project (Example)
Introduction to
Mongoose
Database Integration
There are two approaches for Express apps interacting
with a database:
ORM (Object-Relational Mapping):
Designed for relational databases, such as MySQL,
PostgreSQL, and SQLite.
ORMs map application objects to relational database
tables.
ODM (Object Data Modeling)
Specifically for NoSQL databases, like MongoDB.
ODMS map application objects to database documents.
Database Integration
To connect databases to Express apps, we need
to load an appropriate Node.js driver for the
database in our app
https://expressjs.com/en/guide/database-
integration.html
There are many ODM/ORM solutions available on
the NPM package manager site:
E.g. Mongoose, Waterline, Bookshelf, Objection,
Sequelize
In this course, we will use ODM and Mongoose
Mongoose is a MongoDB object
modeling tool for node.js,
designed to work in an
asynchronous environment
Mongoose provides a straight-
forward, schema-based solution
to model your application data
What is a It includes built-in type casting,
validation, query building,
Mongoose? business logic hooks and more,
out of the box
Map documents coming from a
database into usable JavaScript
objects
Official website:
http://mongoosejs.com/
Define A Schema
Everything in Mongoose starts with a Schema.
Each schema maps to a MongoDB collection
It defines the structures of the documents within
that collection and casting of properties
Guide: https://mongoosejs.com/docs/guide.html
Permitted SchemaTypes
The permitted SchemaTypes are:
String, Number, Date, Buffer, Boolean, Mixed, ObjectId,
Array, Decimal128, Map, UUID, Double, Int32
Reference:
http://mongoosejs.com/docs/schematypes.html
Schema (Example)
var blogSchema = new Schema({
title: String,
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
});
Create A Model
To use our schema definition, we need to convert
our Schema into a Model we can work with
To do so, we pass it into
mongoose.model(modelName, schema)
For example:
const Blog = mongoose.model('Blog', blogSchema);
One Schema/Model per file
We can create schemas and models using any file
structure you like
It is highly recommend defining each model schema in its
own module (file), exporting the method to create the
model
Using a Mongo Database
with Mongoose
Install Mongoose
NOTE: Your MongoDB should be installed before
proceed with this
Create a new project directory called
“IntroToMongoose”
Create a new package.json file (-y will set the default
value for all information)
npm init -y
Install Mongoose using npm:
npm install mongoose --save
Setup Mongoose in a project (1)
Create a new JavaScript file named cats.js :
fsutil file createnew cats.js 0
Open the cats.js file and include the following
codes:
1) Require Mongoose in the project
const mongoose = require('mongoose');
Setup Mongoose in a project (2)
2) Connect to the database
Example: Connect to a catApp database
mongoose.connect("mongodb://localhost/catApp
");
NOTE:
When we run this command, the web server will try
to find catApp database in MongoDB
If the database does not exist, it will create a new
database called ‘catApp’ for us
Setup Mongoose in a project (3)
3) Define your schema in cats.js
Example: Define a schema for cat, the structure
and four properties of a cat document
const catSchema = new mongoose.Schema({
name: String,
age: Number,
breed: String,
temperament: String
});
Setup Mongoose in a project (4)
4) Compiling the schema into a model
Example: Compile the catSchema into a Cat model
and save it as a variable called ‘cat’
const Cat = mongoose.model('Cat', catSchema);
Setup Mongoose in a project (5)
5) Adding a new cat to the database
Option 1: Add a new cat by creating a new
object and using save() method to add it to the
database
Option 2: Adding another new cat to the
database using create() method
Setup Mongoose in a project (6)
Option 1: save() method
const newCat = new Cat({
name: "George",
age: 11,
breed: "Siamese",
temperament: "Grounchy"
});
newCat.save()
.then((newCat) => console.log('New cat saved:', newCat))
.catch((error) => console.error('Error saving new cat:', error));
Setup Mongoose in a project (7)
Option 2: create() method
const newCat2 = {
name: "Handsome",
age: 10,
breed: "Balinese",
temperament: "Active"
};
const cat2 = Cat.create(newCat2)
.then((cat2) => console.log('New cat 2 saved:', cat2))
.catch((error) => console.error('Error saving new cat 2:', error));
Setup Mongoose in a project
Run cats.js
Verify database using basic
MongoDB shell commands
Open a MongoDB shell
Type the following commands to verify the
catApp database, cats collection and
documents:
show dbs
use catApp
show collections
db.cats.find()
Verify database using basic
MongoDB shell commands
Summary
In this lecture, we have covered
An introduction to Mongoose
Install and require mongoose in our project to
connect to MongoDB
Use Mongoose Schema to define the structure
and property of the document in the MongoDB
collection
Compile Mongoose Schema to a Model