Share
Explore

Lab Workbook: Setting Up a Simple Data Model using Mongoose Node API and CRUD Operations on a Mongo Database

This workbook is designed to guide students through the process of setting up a simple data model using the Mongoose Node API.
It includes detailed activities that will help you create, read, update, and delete (CRUD) operations on a Mongo database using Mongoose API calls.

Table of Contents

Introduction to Mongoose and MongoDB
Setting Up the Environment
Creating a Simple Data Model
Implementing CRUD Operations
Conclusion

1. Introduction to Mongoose and MongoDB

Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. It provides a straightforward, schema-based solution to model your application data. MongoDB, on the other hand, is a source-available cross-platform document-oriented database program.

Activity 1

Visit the official Mongoose website () and the MongoDB website () to familiarize yourself with these tools.

2. Setting Up the Environment

Before you start working with Mongoose and MongoDB, you need to set up your environment.

Activity 2

Install Node.js and npm (Node Package Manager) if you haven't already. You can download them from .
Install MongoDB from . Ensure that MongoDB is running on your system.
Install Mongoose using npm by running the command npm install mongoose.

3. Creating a Simple Data Model

Now that you have your environment set up, you can now work on creating your data model using Mongoose.

Activity 3

Create a new file named 'app.js' and require mongoose:

const mongoose = require('mongoose');
Connect to your MongoDB database:
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true, useUnifiedTopology: true});
Define your schema and model:

const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;

const BlogPost = new Schema({
author: ObjectId,
title: String,
body: String,
date: Date
});

const Post = mongoose.model('BlogPost', BlogPost);

4. Implementing CRUD Operations

Now that you have your data model, you can start implementing CRUD operations.

Activity 4

Create: To create a new blog post, you can do:

let post = new Post({ title: 'Example Title', body: 'Example body' });
post.save((err, post) => {
if (err) return console.error(err);
console.log(post.title + " saved to bookstore collection.");
});
Read: To read a blog post:

Post.find((err, posts) => {
if (err) return console.error(err);
console.log(posts);
});
Update: To update a blog post:

Post.updateOne({ title: 'Example Title' }, { title: 'New Example Title' }, (err, res) => {
if(err) return console.error(err);
console.log(res);
});
Delete: To delete a blog post:

Post.deleteOne({ title: 'New Example Title' }, (err) => {
if(err) return console.error(err);
console.log('Deleted successfully');
});

5. Conclusion

Congratulations! You have now set up a simple data model using Mongoose and performed CRUD operations on a MongoDB database. Keep practicing and exploring more functionalities that Mongoose and MongoDB offer.
Remember, the key to mastering any programming language or tool is consistent practice and curiosity. Happy coding!


Lab 2

Learning Outcome:
Write a detailed data model with MONGOOSE NODE API and do create read update delete CRud on a MONGO database and USING MONGOOSE API calls.
https://www.npmjs.com/package/mongoose. Make up an Interesting vertical to provide the example in the context of.
Build a rich MONGO data model such as may be suitable for an Ecommerce Web Application which you will do for your Project.

Mongoose and MongoDB CRUD Operations Workbook

Introduction

Welcome to this student lab learning workbook. In this guide, we will learn how to set up a simple data model using the Mongoose Node.js API. Our practical example will center around an eCommerce web application.
Here's what we'll cover:
Installation and Setup
Building a Data Model
CRUD Operations (Create, Read, Update, Delete)

Prerequisites

Before you start, you should be familiar with:
JavaScript (ES6 syntax)
Node.js
Basic understanding of databases
Let's begin!

Part 1: Installation and Setup

1.1 MongoDB Installation

Firstly, you need to install MongoDB on your machine. Visit MongoDB's official and follow the instructions for your specific operating system.

1.2 Project Setup

To start with, create a new folder on your computer and navigate into it. This folder will be our project directory. Open your terminal/command prompt and navigate into your newly created folder. Then, initialize a new Node.js project:
bashCopy code
npm init -y

1.3 Mongoose Installation

Once the project is initialized, we need to install Mongoose. Still in the terminal, type:
bashCopy code
npm install mongoose

1.4 Connecting to MongoDB

In your project folder, create a new file called server.js. Inside this file, write the following code to establish a connection to your local MongoDB server:
javascriptCopy code
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/ecommerce', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));

With this, we have established a connection to a MongoDB database named 'ecommerce'.

Part 2: Building a Data Model

Mongoose works with data models, which are schemas representing the structure of the underlying data in MongoDB. Let's create a simple Product model for our eCommerce application.
Create a new file called productModel.js and add the following:
javascriptCopy code
const mongoose = require('mongoose');

const ProductSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
description: {
type: String,
},
category: {
type: String,
},
inStock: {
type: Boolean,
default: true
}
});

module.exports = mongoose.model('Product', ProductSchema);

This defines a product with a name, price, optional description and category, and an in-stock status.

Part 3: CRUD Operations

Now that we have our model, let's explore how to perform CRUD operations.

3.1 Create Operation

In our server.js, we will require our model and create a new product. Update your server.js to look like the following:
javascriptCopy code
const mongoose = require('mongoose');
const Product = require('./productModel');

mongoose.connect('mongodb://localhost/ecommerce', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));

// Creating a new product
const product = new Product({
name: 'Sample Product',
price: 99.99,
description: 'This is a sample product',
category: 'Sample Category',
});

product.save()
.then(doc => {
console.log(doc);
})
.catch(err => {
console.log(err);
});

Run the server file:
bashCopy code
node server.js

3.2 Read Operation

To retrieve products from the database, we use the find method on the model:
javascriptCopy code
Product.find({})
.then(docs => {
console.log(docs);
})
.catch(err => {
console.log(err);
});

3.3 Update Operation

To update a product, you can use the findOneAndUpdate method on the model:
javascriptCopy code
Product.findOneAndUpdate(
{ name: 'Sample Product' }, // find a document with that filter
{ price: 89.99 }, // document to insert when nothing was found
{ new: true, upsert: true, runValidators: true }, // options
)
.then(doc => {
console.log(doc);
})
.catch(err => {
console.log(err);
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.