Mongoose Basic for Mongo DB
By: Timothy Chen
Tags: Mongoose, JavaScript, Coding, Mongodb

Getting Started

You need to make sure you have Node.js and Mongo DB installed. In this tutorial, we will use Express and Mongoose. First, we need to install Express and Mongoose on our project using npm :

npm init -y

npm install express mongoose --save

1. Preparing app.js and setting up our connection

We need to import the module needed and configure our port for our project.

//app.js

const express = require("express");

const app = express();

const port = 3000;

app.use(express.urlencoded({ extended: true }));

app.use(express.json());

After that, we need to make a new folder ./config/connection.js on our project root to set our connection to Mongo DB. Let’s say we want to connect to trymongoose server.

//connection.js

const mongoose = require('mongoose')

const uri = 'mongodb://localhost:/trymongoose'

Now, we want to make a function to connect our app with our database, and don’t forget to export the function.

//connection.js

async function connection() {

try {

await mongoose.connect(uri, {useNewUrlParser: true, useUnifiedTopology: true})

console.log('Mongo DB connection - ok')

} catch (err) {

console.log(err)

}

} module.exports = {

connection

}

Next, we need to import our connection function to our app.js to do CRUD operation.

//app.js

const { connection } = require("./config/connection"); connection().then(() => {

app.listen(port, () => {

console.log(`Current Port: ${port}`);

});

});

And to make sure our connection is working properly, we can check our terminal and it should show something like this

Log on our terminal

2. Defining a new schema and create a model

A schema on mongoose defines the shape or structure of a model, such as defining a validator or default value. I would like to make a model called Movies with 2 keys, title and actor. First we need to make a new folder ./models/Movie.js

//Movie.js

const mongoose = require("mongoose"); //defining a new movie schema

const movieSchema = new mongoose.Schema({

title: String, //to make a key with string type

actor: String,

});

We can define our schema with some type such as String, Boolean, Number, etc. To use our schema, we need to make a new model and export it

//creating a new model "movies"

const collection = mongoose.model("movies", moviesSchema); module.exports = collection;

Now we are ready to use our model and do CRUD Operations!

3. CRUD (create-read-update-delete)

First, we need to import our movie model to app.js, so we could access our database.

//app.js

const Movie = require("./models/Movie");

Then, we can try to access our database. To READ from our movie model we can use get method and Model.find() syntax.

app.get("/movies", async (req, res) => {

try {

const movies = await Movie.find(); //accessing movie model

res.send(movies);

} catch (error) {

res.end(err.message)

}

});

To CREATE a new data, we can use post method and .save syntax.

app.post("/movies", async (req, res) => {

try {

const input = new Movie(req.body); //input from request.body

const result = await input.save(); //create new data

res.send(result);

} catch (err) {

res.send(err.message);

}

});

To DELETE one data using id, we can use delete method and deleteOne syntax.

app.delete("/movies/:id", async (req, res) => {//delete data with id

try {

const response = await Movie.deleteOne({ _id: req.params.id });

res.send(response);

} catch (error) {

console.log(error);

}

});

To UPDATE one data using id, we can use put method and updateOne syntax.

app.put("/movies/:id", async (req, res) => {//update data with id

try {

const response = await Movie.updateOne({ _id: req.params.id }, req.body);

res.send(response);

} catch (error) {

console.log(error);

}

});

4. Creating a validator

Mongoose provide a few ways to make a validation before doing CRUD operation using built in validator and creating a custom validator. We want to make a requirement for our movie model :

1. Title

- cannot be empty (required)

- minimum length is 5 character

2. Actor

- can't input with `nobody`

To do that, we need to update our movie schema.

//Movie.js

//Custom validator for actor key

function actorValidator(name) {

return name !== "nobody"

} //using "required" build in validator and custom "actorValidator"

const moviesSchema = new mongoose.Schema({

title: {

type: String,

required: [true, "title field cannot be empty!"]

},

actor: {

type: String,

validate: [actorValidator, "please input a valid name!"]

},

});

When we input a new data with empty title, the expected outcome is a error message “title field cannot be empty!” and with “nobody” value on actor, error message “”please input a valid name!” would show up.