0

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! :)

Redtama
  • 1,603
  • 1
  • 18
  • 35
  • All these MongoDB calls are asynchronous. You cannot use your variable before they have completed. – Thilo Nov 21 '16 at 01:31
  • @Thilo does that mean that I should be putting all my code inside of mongodb connect callback when the connection is successful? – Redtama Nov 21 '16 at 01:33
  • That would be one way, but will become very tedious very soon. Look at Promises or some other library to help work with asynchronous computations. http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call?rq=1 – Thilo Nov 21 '16 at 01:34
  • 1
    @Thilo Aha ok thanks. I will do some more research. Maybe someone will post an answer using one of those in the meantime :) – Redtama Nov 21 '16 at 01:36
  • Look at [Node.js, Mongo find and return data](http://stackoverflow.com/questions/35246713/node-js-mongo-find-and-return-data) – Thilo Nov 21 '16 at 01:37
  • Could use promises, or call back function. I've found this very helpful, http://stackoverflow.com/questions/35246713/node-js-mongo-find-and-return-data – Ramon Rahman Apr 13 '17 at 12:37

0 Answers0