I'm making a trading card game similar to Hearthstone or Magick the Gathering.
In MongoDB I am storing my Card data. Each unique card has a name, attack, health and cost.
Upon running the app on the server, I want to connect to the database, read in all the card data and store it in an array of UniqueCard objects. The array is declared as a static variable on my UniqueCard class so it is accessed with UniqueCard.uniqueCards
.
The problem I am having is that once I've connected to the database and populated my unique cards array, it doesn't seem to persist once I close the connection.
Clearly I'm misunderstanding something about the way I should be using the MongoClient in my javascript but I'm not sure what.
Here is my app.js
/** app.js **/
var express = require('express');
var app = express();
var server = require('http').Server(app);
var MongoClient = require('mongodb').MongoClient;
// Import Game Controller
GameController = require('./server/js/Controllers/GameController');
app.get('/', function (req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client', express.static(__dirname + '/client'));
server.listen(80);
// Database Connection
MongoClient.connect('mongodb://localhost:27017/cards', function (err, db) {
if (err) {
console.log("Failed to connect to database.", err);
} else {
db.collection('cards').find().toArray(function (err, result) {
if (err) {
console.log("No documents found.");
} else {
result.forEach(function (data) {
UniqueCard.uniqueCards.push(new UniqueCard(data));
});
console.log(UniqueCard.uniqueCards); //This prints my data.
db.close();
}
});
}
});
console.log(UniqueCard.uniqueCards); //This prints an empty array but why??
var gameController = new GameController();
gameController.startMatch();
And here is UniqueCard.js:
/** UniqueCard.js **/
/* Constructor */
var UniqueCard = function (data) {
this.name = data.name;
this.attack = data.attack;
this.health = data.health;
this.cost = data.cost;
};
/* Static Variables */
UniqueCard.uniqueCards = [];
module.exports = UniqueCard;
My UniqueCard module gets included in my app.js since it is required in my GameController.js file.
Any help is much appreciated! Thank you! :)