Share
Explore

Lab Recipes: MONGOOSE API Programming

Node.js and MongoDB using Mongoose
Let's imagine you're a chef, ready to create a scrumptious meal, but in this case, the meal is a simple yet effective Mongoose API: Mogoose is the Node.js API package to connect to a MONGO database from JavaScript Code.

Step 1: Setting Up the Kitchen (Visual Studio Code and Project Setup)
Install Visual Studio Code: It's like choosing the right kitchen for our cooking. If you haven't already, download and install it from .
Create a New Folder: This will be your project folder. Right-click in your desired directory and select 'New Folder'.
Open the Folder in VS Code: Open VS Code, go to 'File' > 'Open Folder', and select the folder you just created.
Initialize Your Project: Open the terminal in VS Code (Terminal > New Terminal) and type npm init. This is like laying out your ingredients. Follow the prompts to create your package.json file.
Step 2: Gathering Ingredients (Installing Dependencies)
Install Node.js: If you haven’t already, install Node.js from .
Install Dependencies: In your terminal, run:
bashCopy code
npm install express mongoose body-parser
These are the ingredients for our API: Express for the server, Mongoose for MongoDB interactions, and Body-Parser for parsing incoming request bodies.
Step 3: Preparing the Recipe (Writing the Code)
Create a File for the Server: In your project folder, create a file named server.js.
Write the Server Code: Here’s a simple server setup:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());

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

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connected successfully to MongoDB");
});

// Define the Student schema

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.