db.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /**
  2. * Created by root on 2015-07-20.
  3. */
  4. var MongoClient = require('mongodb').MongoClient
  5. , assert = require('assert');
  6. var database;
  7. // Connection URL
  8. var url = 'mongodb://localhost:27017/Behavior';
  9. // Use connect method to connect to the Server
  10. module.exports.active = function(callback){
  11. MongoClient.connect(url, function(err, db) {
  12. if (!err){
  13. console.log("Connected correctly to server");
  14. database = db;
  15. }
  16. callback(err);
  17. });
  18. };
  19. module.exports.getCollection = function(name, callback){
  20. if (!database && !database.connected)
  21. callback(database.collection(name));
  22. database.collection(name, {strict:true}, function(err, collection) {
  23. if (!err)
  24. callback(err, collection);
  25. else{
  26. // Create the collection
  27. database.createCollection(name, function(err, result) {
  28. // Retry to get the collection, should work as it's now created
  29. if (!err)
  30. database.collection(name, {strict:true}, callback);
  31. });
  32. }
  33. });
  34. };