Getting started with MongoDB/Mongoose

Benjamin Ajewole
3 min readDec 13, 2019

--

What is MongoDB?

MongoDB is a document database with the scalability and flexibility that you want with the querying and indexing that you need. It is a NoSQL database. Instead of using tables and rows in a relational database, you will use collections and documents.

What is Mongoose?

Mongoose is an elegant MongoDB object modelling for Node.js. It provides an Object Data Modeling (ODM) environment that wraps the Node.js native driver. It makes it easier to use MongoDB with Nodejs.

To set your local environment ready for MongoDB

Install MongoDB on your local machine. Install MongoDB for Windows, Mac, Ubuntu

To check if MongoDB was installed successfully, open your command-line interface and execute mongod --version and mongo --version

For Windows users, you will need to use the full path like"C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe" --version and "C:\Program Files\MongoDB\Server\4.2\bin\mongo.exe" --version

To start a MongoDB server

For Mac, enter this command, mongod

For Linux, enter this command, sudo service mongodb start

For Windows users, enter this command C:\Program Files\MongoDB\Server\4.2\bin\mongo.exe

To create a database

For Mac and Linux users, create a database called learnmongo with this commanduse learnmongo. You can also use use <database-name> to navigate to a specific database.

For Windows users, create a database directory where MongoDB stores data

cd C:\
md "\data\db"

Start your MongoDB database

"C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe" --dbpath="c:\data\db"

Connect your MongoDB

"C:\Program Files\MongoDB\Server\4.2\bin\mongo.exe"

Create a database called learnmongo with this commanduse learnmongo. You can also use use <database-name> to navigate to a specific database.

Create a Nodejs Server

After setting up MongoDB locally, let’s write some codes. I assume you have worked with Nodejs before now.

Create an app.js and add this line of code to get our server running

Make sure you install express npm i express

Run node app.js to start the server. Go to your browser/postman to test localhost:40001, Welcome to learning MongoDB will be printed on your screen.

Install Mongoose in your project, npm i mongoose.

Require mongoose, connect to your local database and initialize your schema

// require mongooseconst mongoose = require("mongoose");// connect your databasemongoose.connect("mongodb://localhost:27017/learnmongo", {useNewUrlParser: true});const Schema = mongoose.Schema;

Create your Schema, it’s like rows in SQL database

// create the schemaconst StudentSchema = new Schema({name: String,age: Number});

Create your Model with the StudentSchema

const StudentModel = mongoose.model("Students", StudentSchema);

Get all Students

To get all the documents from a particular collection, use find()

app.get("/students", async (req, res) => {try {const students = await StudentModel.find();res.status(200).json({no_of_students: students.length,students});} catch (error) {return error;}});

Add new students

To populate a particular collection, use create()

To create an endpoint to add new students, add a middleware to parse your request body into a JSON format

app.use(express.json());

Then,

app.post("/students", async (req, res) => {try {const student = await StudentModel.create(req.body);res.status(201).json({student});} catch (error) {return error;}});

Go to Postman and make a post request with this body

{
"name": "Ben",
"age": 10
}

Get a student by id

To get a document by its id, use findById()

app.get(`/students/:students_id`, async (req, res) => {try {const student = await StudentModel.findById(req.params.students_id);res.status(200).json({student});} catch (error) {return error;}});

Update a student by Id

To update an item by its id, use findByIdAndUpdate()

// { new: true } make sure mongoDB to return the the updated documentapp.put(`/students/:students_id`, async (req, res) => {try {const student = await StudentModel.findByIdAndUpdate(req.params.students_id,req.body,{ new: true });res.status(201).json({ student});} catch (error) {return error;}});

Delete a student by id

To delete or remove a document by id, use findByIdAndRemove()

app.delete(`/students/:students_id`, async (req, res) => {try {await StudentModel.findByIdAndRemove(req.params.students_id);res.status(204).json({message: "Document deleted successfully"});} catch (error) {return error;}});

Final code here

You can query your database outside using CLI or MongoDB Compass.

Using CLI

For Mac and Linux users, enter mongo on your CLI to launch MongoDB shell.

For Windows users, enter C:\Program Files\MongoDB\Server\4.2\bin\mongo.exe on your CLI to launch MongoDB shell.

Using MongoDB Compass

Go to https://www.mongodb.com/products/compass to get started.

--

--

No responses yet