I am using NodeJS together with MongoDB and have some issues with passing the mongoDB object to all my prototype functions. I don't understand how to pass this object between these prototypes. Maybe someone could point me in the right direction?
In my main file I create a new instance of my mongoDB object which contains all the prototypes I want to use to work with mongoDB. Then I use the prototype functions to connect and to create a new collection.
Main.js
var mongo = require('./database/mongoDB')
var mongoDB = new mongo();
// Connect to database
mongoDB.ConnectDB(dbPath);
// Create a collection
mongoDB.CreateNewCollection("Usernames");
The prototype functions are defined in MongoDB.js
MongoDB.js
// Get mongoDB
var mongoDB = require('mongodb').MongoClient;
var DatabaseOperations = function () {}; // Constructor
DatabaseOperations.prototype.ConnectDB = function(dbPath){
// Connect to database
mongoDB.connect(dbPath, function(err, mongoDatabase) {
if(!err) {
console.log("Connected to database: " + dbPath);
mongoDB.database = mongoDatabase;
} else {
console.log("Could not connect to database, error returned: " + err);
}
});
}
DatabaseOperations.prototype.CreateNewCollection = function(collectionName){
mongoDB.database.createCollection(collectionName, function(err, collectionName){
if(!err) {
console.log("Successfully setup collection: " + collectionName.Username);
mongoDB.collectionName = collectionName;
} else {
console.log("Could not setup collection, error returned: " + err);
}
});
}
I am able to connect to the database but from there on, I do not know how to pass the database object to other prototype functions in order to create a collection or do anything else with it. The error message I get when running it is this:
mongoDB.database.createCollection(collectionName, function(err, collection
TypeError: Cannot read property 'createCollection' of undefined
How do I get the database object into each of the prototype functions to work with it?
I see you found an alternative solution, but I'm going to comment anyway. Inside the constructor you should be doing something like
This way, you are assigning the database to the DatabaseOperations, and every prototype function of DatabaseOperations will have access to it through this.database. The database is now a property of the object. In general, different functions can only see stuff assigned to 'this' (DatabaseOperations).