Section 26 – Lessons 351 & 352 – Complete 2020 Web Development Bootcamp

Lesson 351 – Introduction to Mongoose

Mongoose is an ODM – an Object Document Mapper.

Mongoose allows your node.js app which speaks the language of Javascript objects to talk to your mongoDB database which speaks the language of documents, collections and databases.

In the mongo shell, in order to delete the entire fruits database you first have to switch to that database using this code –

use fruitsDB

You then run the dropDatabase() command using this code –

db.dropDatabase()

You will get this confirmation message –

{ "dropped" : "fruitsDB", "ok" : 1 }

Once the fruits database is deleted, the next step is to install the mongoose npm in the fruits directory. First, make sure that you are in the fruits directory in the Hyper terminal and then type –

npm i mongoose

In your app.js file, you then have to insert this code to require mongoose and connect to and create your mongoDB database –

const mongoose = require('mongoose');

mongoose.connect("mongodb://localhost:27017/fruitsDB", {useNewUrlParser: true, useUnifiedTopology: true});

The above code can be found on the Mongoose website.

The next step is to insert some data. The first thing you need to do is create a new schema with this code –

const fruitSchema = new mongoose.Schema ({
	name: String,
	rating: Number,
	review: String
});

Once you create the schema, you use the schema to create a mongoose model. This is the code –

const Fruit = mongoose.model("Fruit", fruitSchema);

Now you are ready to create a new fruit document using this code –

const fruit = new Fruit ({
	name: "Apple",
	rating: 7,
	review: "Pretty good!"
});

Next you call the .save() command like this –

fruit.save();

The challenge in this lesson is to create a new collection of people. You have to create the schema with two fields (name & age), the model and the document.

To complete this challenge, you can use this code –

const personSchema = new mongoose.Schema ({
	name: String,
	age: Number
});

const Person = mongoose.model("Person", personSchema);

const person = new Person ({
	name: "John",
	age: 37
});

person.save();

To insert a number of items at the same time, you first create the items. In this case, you will create three more fruits with this code –

const kiwi = new Fruit ({
	name: "Kiwi",
	rating: 10,
	review: "The best fruit!"
});

const orange = new Fruit ({
	name: "Orange",
	rating: 8,
	review: "Nice!"
});

const banana = new Fruit ({
	name: "Banana",
	rating: 7,
	review: "I like it!"
});

Then you use the .insertMany() command to insert them all at the same time. This is the code –

Fruit.insertMany([kiwi, orange, banana], function(err) {
	if (err) {
		console.log(err);
	} else {
		console.log("Successfully saved all the fruits to fruitsDB!");
	}
});

This is the new app.js file code after the changes made in this lesson to incorporate Mongoose –

const mongoose = require('mongoose');

mongoose.connect("mongodb://localhost:27017/fruitsDB", {useNewUrlParser: true, useUnifiedTopology: true});

const fruitSchema = new mongoose.Schema ({
	name: String,
	rating: Number,
	review: String
});

const Fruit = mongoose.model("Fruit", fruitSchema);

const fruit = new Fruit ({
	name: "Apple",
	rating: 7,
	review: "Pretty good!"
});

const personSchema = new mongoose.Schema ({
	name: String,
	age: Number
});

const Person = mongoose.model("Person", personSchema);

const person = new Person ({
	name: "John",
	age: 37
});

person.save();

const kiwi = new Fruit ({
	name: "Kiwi",
	rating: 10,
	review: "The best fruit!"
});

const orange = new Fruit ({
	name: "Orange",
	rating: 8,
	review: "Nice!"
});

const banana = new Fruit ({
	name: "Banana",
	rating: 7,
	review: "I like it!"
});

Fruit.insertMany([kiwi, orange, banana], function(err) {
	if (err) {
		console.log(err);
	} else {
		console.log("Successfully saved all the fruits to fruitsDB!");
	}
});

Lesson 352 – Reading from your Database with Mongoose

To read data from your mongoDB database with Mongoose you can use the .find() command. If you want to find all the data in your fruits collection you can use –

Fruit.find(function(err, fruits) {
	if (err) {
		console.log(err);
	} else {
		
		console.log(fruits);
	
	}
});

The challenge in this lesson is to create a forEach loop that will console log the name of each fruit in the array. The solution to this challenge is –

Fruit.find(function(err, fruits) {
	if (err) {
		console.log(err);
	} else {
		fruits.forEach(function(fruit) {
		console.log(fruit.name);
	});
	}
});

In order to close the database connection once you have confirmed that there are no errors, you put this code at the beginning of the else statement in the Fruit.find() command –

mongoose.connection.close();

The Fruit.find() com with the .close() command looks like this –

Fruit.find(function(err, fruits) {
	if (err) {
		console.log(err);
	} else {

		mongoose.connection.close();

		fruits.forEach(function(fruit) {
		console.log(fruit.name);
	});
	}
});