Reader small image

You're reading from  Hands-on JavaScript for Python Developers

Product typeBook
Published inSep 2020
Reading LevelIntermediate
PublisherPackt
ISBN-139781838648121
Edition1st Edition
Tools
Right arrow
Author (1)
Sonyl Nagale
Sonyl Nagale
author image
Sonyl Nagale

Chicago-born, Iowa-raised, Los Angeles-seasoned, and now New York City-flavored, Sonyl Nagale started his career as a graphic designer focusing on web, which led down the slippery slope to becoming a full-stack technologist instead. With an eye toward the client use case and conversation with the creative side, he prides himself on taking a holistic approach to software engineering. Having worked at start-ups and global media companies using a variety of languages and frameworks, he likes solving new and novel challenges. Passionate about education, he's always excited to have great teachable moments complete with laughter and seeing the Aha! moments in students eyes.
Read more about Sonyl Nagale

Right arrow
Node.js and MongoDB

You may have heard of the MEAN stack: MongoDB, Express, Angular, and Node.js, or the MERN stack: MongoDB, Express, React, and Node.js. The missing piece that we have yet to discuss is MongoDB. Let’s explore how this NoSQL database can be used directly from Express. We'll be constructing the next iteration of our starship game that we started in Chapter 13, Using Express, except this time using MongoDB and incorporating a bit of testing!

We will cover the following topics in this chapter:

  • Using MongoDB
  • Testing with Jest
  • Storing and retrieving data
  • Wiring your API together

Technical requirements

Using MongoDB

The base premise behind MongoDB that makes it different from other types of structured key/value pair databases is that it's schemaless: you can insert arbitrary documents of unstructured data without concern for what another entry in the database looks like. A document in NoSQL parlance is something already familiar to us: a JavaScript object!

Here's a document:

{
"first_name": "Sonyl",
"last_name": "Nagale",
"role": "author",
"mood": "accomplished"
}

We can see that it's a basic JavaScript object; more specifically, it's JSON, which means it can also support nested data. Here's an example:

{
"first_name": "Sonyl",
"last_name": "Nagale",
"role": "author",
"mood": "accomplished",
"tasks": {
"write": {
"status": "incomplete"
},
"cook": ...

Storing and retrieving data

Let's work with a test suite that I wrote to help make sure that our MongoDB connection is a bit more robust and includes inserting data into the database and then testing to be sure it exists:

  1. Examine test/setup.model.test.js:
const MongoDB = require('../models/mongo')
const insertRandomNames = require('../models/setup')

describe('insert', () => {
let db

beforeAll(async () => {
db = await MongoDB.connectDB('test')
})

afterAll(async (done) => {
await db.collection('names').deleteMany({})
await MongoDB.disconnectDB()
done()
})

it('should insert the random names', async () => {
await insertRandomNames()

const names = await db.collection("names").find().toArray()
expect(names.length).toBeGreaterThan(0)
})

})
  1. If we run node_modules/.bin/jest setup, we'll see success because the insertRandomNames() method exists from our setup model. So let's take a look...

Wiring your API together

To further understand the gameplay, we'll walk through the steps involved in firing a torpedo from a ship:

  1. Locate the frontend JavaScript in public/javascripts/play.js:
document.querySelectorAll('.fire').forEach((el) => {
el.addEventListener('click', (e) => {
const weapon = (e.target.classList.value.indexOf('fire-torpedo')
> 0) ? "torpedo" : "phasers"
const target = e.target.parentNode.getElementsByTagName
('select')[0].value
  1. Here we've made a click handler on the fire buttons in our interface and identified our weapon and target ship:
fetch(
`/play/fire? attacker=${e.target.closest('td').dataset.attacker}&target=${target}&weapon=${weapon}`)
.then(response => response.json())
.then(data => {

This line might take a bit of unpacking. We're making an AJAX call to our Node application from our JavaScript with certain query string parameters: attacker...

Summary

JavaScript doesn't exist in isolation! MongoDB is a great companion to JavaScript as it is designed to be object-oriented and relies on a JavaScript-friendly querying syntax. We've learned the principles behind TDD, worked with the MVC paradigm, and expanded our game a bit more.

As with all coding exercises, be sure to consider the use cases when using a database such as MongoDB: while MongoDB's syntax isn't vulnerable to SQL injections, it is still vulnerable to other types of injections that can compromise your application.

Hopefully, our starship game is interesting enough for you to keep developing it. Our next (and final) chapter wraps together our principles of JavaScript development and polishes our game.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Hands-on JavaScript for Python Developers
Published in: Sep 2020Publisher: PacktISBN-13: 9781838648121
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Sonyl Nagale

Chicago-born, Iowa-raised, Los Angeles-seasoned, and now New York City-flavored, Sonyl Nagale started his career as a graphic designer focusing on web, which led down the slippery slope to becoming a full-stack technologist instead. With an eye toward the client use case and conversation with the creative side, he prides himself on taking a holistic approach to software engineering. Having worked at start-ups and global media companies using a variety of languages and frameworks, he likes solving new and novel challenges. Passionate about education, he's always excited to have great teachable moments complete with laughter and seeing the Aha! moments in students eyes.
Read more about Sonyl Nagale