Skip to content

Using MongoDB

odoland edited this page Nov 16, 2018 · 1 revision

MongoDB

Our database is stored here (the SandBox account - 0.5 GB with no backups) https://mlab.com/

Quick summary: It's a NoSQL - so they are just documents and they are stored as JSON objects (key-value pairs) NoSQL Explained

We have a users collection currently, and each item is just a JSON, like that: { username: "mary" password: "littlelamb" }


MongoDB code:

substitute and with a database user/password (set one up @ mlab.com) Starting up the mongoClient dependencies and initialization

var mongodb = require('mongodb');
const mongoClient = mongodb.MongoClient;
const url = 'mongodb://<dbuser>:<dbpassword>@ds163013.mlab.com:63013/cardsagainsthumanity';

Code to connect to to the database

mongoClient.connect(url, {useNewUrlParser: true}, function (err, db) {
   if (err) {
      console.log ("Error connecting to mongo" + err);
   } else {
      console.log("Successfully connected);
   }
   
   // Now within the body of this connect, you can do stuff
   doStuff();
});

Replace doStuff() with stuff you want to do:

Accessing a collection in the database, 'cardsagainsthumanity' called 'users':

const cahDB = db.db('cardsagainsthumanity');
const userCollection =cahDB.collection('users);

Finding an entry in the collection, like the username:

userCollection.find({username: "mary"}).toArray((err,dbResult) {
   if (err) {
    // handle error
   } else if (dbResult.length) {  // equivalent to if dbResult.length != 0;
    // do something if result is non-zero length (not empty)
   } else {
     // do something is nothing is found
   }

More cheatsheets: Beginner mongodb examples

How it Works

This is a single web-page application built with Node.js, Express, MongoDB and SocketIO. Each section has a div / section which is changed in the css to display (or hide)

Login & Registration

Login and Registration is done by connecting to a MongoDB NoSQL database hosted at mlabs.

Lobby is refreshed to print out all the online players in the lobby. Upon connection, players are added onto . Each socket.id becomes the key, and their username is a value.

var totalOnlinePlayers = {}; // {socket.id:username}

Lobby

The Lobby chatroom sends the client's message to the server. The server receives it through:

socket.on('updateChatbox', (message, sender) => updateChatbox(socket, message, sender));

which will broadcast the message to all other clients to update the HTML (client side) to display the chat message.

Custom Cards Page & Cards

Card values and text are stored in .txt files on the server, under the Classes/ directory.

Classes/promptcards.txt
Classes/playercards.txt
Classes/array.txt

They hold the player's custom cards and the default and player cards.

Game Logic

Client clicks any card -> sends the index to the server, which stores the card values of the card.

Clone this wiki locally