Example #1
0
/**
 * Main application file
 */

'use strict';

import express from 'express';
import mongoose from 'mongoose';
mongoose.Promise = require('bluebird');
import config from './config/environment';
import http from 'http';

// Connect to MongoDB
mongoose.connect(config.mongo.uri, config.mongo.options);
mongoose.connection.on('error', function(err) {
  console.error('MongoDB connection error: ' + err);
  process.exit(-1);
});

// Populate databases with sample data
if (config.seedDB) { require('./config/seed'); }

// Setup server
var app = express();
var server = http.createServer(app);
var socketio = require('socket.io')(server, {
  serveClient: config.env !== 'production',
  path: '/socket.io-client'
});
require('./config/socketio').default(socketio);
require('./config/express').default(app);
require('./routes').default(app);
Example #2
0
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

var Test = require('./models/test');
var TestOne = require('./models/testOne');


//connect to mongodb
mongoose.connect('mongodb://127.0.0.1:27017/Edge');

mongoose.connect('mongodb://test:password@ds211558.mlab.com:11558/ionic_chat');

//on successful connection
mongoose.connection.on('connected', () => {
	console.log('Connected to mongodb!!');
});

//on error
mongoose.connection.on('error', (err) => {
	if (err) {
		console.log('Error in db is :' + err);
	}
});

let array = [];

io.on('connection', function (client) {
	console.log("Socket connected !");

	client.on("generate", function (data) {
Example #3
0
/**
 * Created by dbuarque on 2/24/16.
 */
// Bring Mongoose into the app
import mongoose from 'mongoose';

const MONGO_URL = process.env.MONGO_URL || 'mongodb://localhost/basicapi';

mongoose.connect(MONGO_URL);

mongoose.connection.on('connected', function () {
    console.log('Mongoose default connection open to ' + MONGO_URL);
});

mongoose.connection.on('error',function (err) {
    console.log('Mongoose default connection error: ' + err);
});

mongoose.connection.on('disconnected', function () {
    console.log('Mongoose default connection disconnected');
});

process.on('SIGINT', function() {
    mongoose.connection.close(function () {
        console.log('Mongoose default connection disconnected through app termination');
        process.exit(0);
    });
});
Example #4
0
process.once('SIGUSR2', function(){
  mongoose.connection.close(function(){
    console.log("Mongoose disconnected through app termination. (SIGUSR2)");
    process.kill(process.pid, 'SIGUSR2');
  });
});
Example #5
0
var app = express();

// link css and jss folder
app.use(express.static(__dirname + '/public'));

// suppoert json data and body data
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());


//database connection
var dbURI = 'mongodb://localhost/newcrud';
// Create the database connection 
mongoose.connect(dbURI);
mongoose.connection.on('connected', function () {  
  console.log('Mongoose default connection open to  ' + dbURI);
}); 
mongoose.connection.on('error',function (err) {  
  console.log('Mongoose default connection error: ' + dbURI);
}); 
mongoose.connection.on('disconnected', function () {  
  console.log('Mongoose default connection disconnected' + dbURI); 
});

// database schema
var Schema = mongoose.Schema;
var userSchema = new Schema({
  first : String ,
  last: String,
  age: Number,
  gender: String,
Example #6
0
var gracefulShutdown = function (msg, callback) {
    mongoose.connection.close(function () {
        console.log('Mongoose disconnected through ' + msg);
        callback();
    });
};
Example #7
0
//Using mongoose
var mongoose = require('mongoose');
var dburl = "mongodb://localhost:27017/meanhotel";

mongoose.connect(dburl);

mongoose.connection.on('connected', function(){
  console.log("Mongoose connected to ", dburl);
});
mongoose.connection.on('disconnected', function(){
  console.log("Mongoose disconnected.");
});
mongoose.connection.on('error', function(err){
  console.log("Mongoose connection error : " + err);
});

process.on('SIGINT', function(){
  mongoose.connection.close(function(){
    console.log("Mongoose disconnected through app termination. (SIGINT)");
    process.exit(0);
  });
});

process.on('SIGTERM', function(){
  mongoose.connection.close(function(){
    console.log("Mongoose disconnected through app termination. (SIGTERM)");
    process.exit(0);
  });
});

process.once('SIGUSR2', function(){
      memStore: config.db.memStore,
      searchInArray: true,
      nativeObjectID: false
   };
}
var mongoose = require('mongoose');
var fs = require('fs');

try {
   if (!isEmbedded) {
      verboseLog("Using MongoDB for database.");
      mongoose.connect(config.db.mongoUrl);
      mongoose.connection.on('error', function(err) {
         if (err.message == 'connect ECONNREFUSED') {
            console.warn('Error: Could not connect to MongoDB server. Is MongoDB server running?');
            process.exit(1);
         }
         else
            console.warn(err.message);
      });
   }
   else {
      var absPath = setupDatabaseDirectory();
      mongoose.connect('tingodb://'.concat(absPath));
   }

   mongoose.connection.on('error', onError);
   mongoose.connection.once('open', function() {
      console.timeEnd("Database ready");
   });
}
catch(e) {
Example #9
0
    // //Si erreur de connexion
    // db.on('error', console.error.bind(console, 'connection error:'));
    //
    // db.once('open', function() {
    //
    //
    //   Employes.find(function(err,employes){
    //     if (err) return console.error(err);
    //     var message = 'Les employées: '+employes;
    //     console.log(employes);
    //     res.setHeader('Content-Type', 'text/plain');
    //     res.end(message);
    //   });
    // });
    Employes.find({}, function (err, docs) {
        res.json(docs);
    });
});

//Fiche d'un employé selon son id
app.get('/collaborateurs/:id', function(req, res) {
    var message = 'Ici les infos de l\'employe :'+req.params.id;
    res.setHeader('Content-Type', 'text/plain');
    res.end(message);
});

app.listen(80);
//fermeture de la base
mongoose.connection.close();
Example #10
0
const gracefulShutdown = (msg, callback) => {
    mongoose.connection.close(() => {
        log.info(`Mongoose disconnection through ${msg}`);
        callback();
    });
};
Example #11
0
	path            = require('path'),
	hapi            = require('hapi'),
	mongoose        = require('mongoose'),
	maths           = require('../lib/maths.js'),
	Store           = require('../lib/store.js').Store,
	utils           = require('../lib/utilities.js'),
	pack            = require('../package');



// moungodb connection for store
var connection = mongoose.createConnection('mongodb://127.0.0.1/be-more-hapi'),
	store = new Store(mongoose, connection);

mongoose.connection.on('error', function (err) {
  console.log(['error'], 'moungodb connect error: ' + err);
});


/* ----------------------------------------------------------------------------------- */


function index(request, reply) {
	utils.getMarkDownHTML(__dirname.replace('/lib','') + '/README.md', function(err, data){
		reply.view('swagger.html', {
			title: pack.name + ' — Calculator',
			markdown: data
		});
	});
}
Example #12
0
if (process.platform === 'win32') {
    const rl = readLine.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    rl.on('SIGINT', () => {
        process.emit('SIGINT');
    });
}

/*  CONNECTION EVENTS
    Monirtoring for successful connection through Mongoose
*/
mongoose.connection.on('connected', () => {
    log.info(`Mongoose connected to ${dbUri}`);
});

/*  Checking for connection error */
mongoose.connection.on('error', (err) => {
    log.info(`Mongoose connection error ${err}`);
});

/*  Checking for disconnection event */
mongoose.connection.on('disconnected', () => {
    log.info('Mongoose is disconnected');
});

/*  CAPTURE APP TERMINATION / RESTART EVENTS */
const gracefulShutdown = (msg, callback) => {
    mongoose.connection.close(() => {
Example #13
0
var express = require('express')
var mongoose = require('mongoose')
var morgan = require('morgan')
var passport = require('passport')
var skipper = require('skipper')
var colors = require('colors')
var path = require('path')

// Configure Mongoose

// mongoose.connect('mongodb://mongodb.cs.dixie.edu/SudoBashBash')
mongoose.connect('mongodb://localhost/todos')
mongoose.connection.on('connected', function () {
  console.log('Mongoose connected...'.green)
})
mongoose.connection.on('error', function (err) {
  console.log('Mongoose connection failed... \n'.red + err)
})

require('./server/config/passport')

// Configure Express

var app = express()

app.use(express.static(__dirname + '/dist'))

app.use(morgan('dev'))
//app.use(passport.initialize())
app.use(skipper())
Example #14
0
const moment = require('moment');
const _ = require('lodash');

// const Group = mongoose.model('Group'),
// const Event = mongoose.model('Event'),
// const Notification = mongoose.model('Notification'),
const FsFile = require('../models/fsfile');
// const Friendship = mongoose.model('Friendship'),
const User = require('../models/user');

const ObjectId = mongoose.Types.ObjectId;
Grid.mongo = mongoose.mongo;
// console.log(mongoose.mongo);
let gfs = null;
mongoose.connection.once('open', () => {
  gfs = new Grid(mongoose.connection.db);
});

function createImage(user, file, group, type, res, callback) {
  file.path = `/uploaded/files/${user.email}/${file.name}`;
  if (process.env.NODE_ENV === 'test') {
    file.path = `${__dirname}/../tests/testing_files/${file.name}`;
  }
  const imageTransformer = sharp().resize(640, 640).max().rotate().progressive().quality(85).toFormat('jpeg');
  const fileReadStream = fs.createReadStream(file.path);

  const gridFile = {
      filename: file.name,
      content_type: file.type,
      metadata: {
        uploader: user._id,
Example #15
0
 mongoose.connection.db.dropDatabase(function () {
   console.error('closing db connection');
   mongoose.connection.close();
 });
Example #16
0

//------------ Express Routes ------------//
app.use('/favorites', favorites);
app.use('/register', register);
app.use('/user', user);
app.use('/', index);


//------------ Database Connection ------------//

var databaseURI = 'mongodb://localhost:27017/MEAN_SEED';


console.log('DB: ', databaseURI);
mongoose.connect(databaseURI);

mongoose.connection.on('connected', function() {
    console.log('Mongoose connection open ', databaseURI);
});

mongoose.connection.on('error', function(err) {
    console.log('Mongoose error connecting ', err);
});

//------------ Set Port & Start Server ------------//
app.set('port', process.env.PORT || 1234);
app.listen(app.get('port'), function() {
    console.log('listening on port: ', app.get('port'));
});
        {name: "Blue Man Group", place: [new Place({address: "434 Lafayette St", city: "New York", state: "NY", phone: "123-456-7890", location: [40.729373, -73.992104]})], age_range: "All" },
        {name: "Scott's Pizza Tours", place: [new Place({address: "244 5th Ave", city: "New York", state: "NY", phone: "123-456-7890", location: [40.744610, -73.987708]})], age_range: "All" },
        {name: "Apple Store", place: [new Place({address: "103 Prince St", city: "New York", state: "NY", phone: "123-456-7890", location: [40.724918, -73.999144]})], age_range: "All" },
        {name: "Brooklyn Bridge Park", place: [new Place({address: "Pier 1", city: "New York", state: "NY", phone: "123-456-7890", location: [40.702225, -73.996563]})], age_range: "All" },
        {name: "Ellis Island Immigration Museum", place: [new Place({address: "Ellis Island", city: "New York", state: "NY", phone: "123-456-7890", location: [40.699297, -74.040317]})], age_range: "All" },
        {name: "Washington Square Park", place: [new Place({address: "1 Washington Sq E", city: "New York", state: "NY", phone: "123-456-7890", location: [40.732204, -73.998649]})], age_range: "All" },
        {name: "Union Square Holiday Market", place: [new Place({address: "Union Sq & W 14th St", city: "New York", state: "NY", phone: "123-456-7890", location: [40.733615, -73.987995]})], age_range: "All" },
        {name: "Strand Bookstore", place: [new Place({address: "828 Broadway", city: "New York", state: "NY", phone: "123-456-7890", location: [40.733274, -73.990870]})], age_range: "All" }
    ]
};
 
mongoose.connection.on('open', function() {
    mongoose.connection.db.dropDatabase(function() {
        
        console.log("Dropped old data, now inserting data");
        async.each(Object.keys(data),
            function(modelName, outerDone) {
                async.each(data[modelName],
                    function(d, innerDone) {
                        models[modelName].create(d, innerDone);
                    },
                    outerDone
                );
            },
            function(err) {
                console.log("Finished inserting data");
                console.log("Control-C to quit");
            }
        );
    });
});
Example #18
0
 * API keys and Passport configuration.
 */
var secrets = require('./config/secrets');
var passportConf = require('./config/passport');

/**
 * Create Express server.
 */
var app = express();

/**
 * Connect to MongoDB.
 */
mongoose.connect(secrets.db);
mongoose.connection.on('error', function() {
  console.error('MongoDB Connection Error. Please make sure that MongoDB is running.');
});

/**
 * Express configuration.
 */
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(compress());
app.use(connectAssets({
  paths: [path.join(__dirname, 'public/css'), path.join(__dirname, 'public/build/js'), path.join(__dirname, 'public/js')]
}));
app.use(logger('dev'));
app.use(favicon(path.join(__dirname, 'public/favicon.png')));
app.use(bodyParser.json());
Example #19
0
// load environment variables
try {
  dotenv.load({
    path: environment_variables_file
  });
  logger.logInfo(module_name, 'environment variables loaded');
}
catch(e) {
  errorExit('dotenv', 'could not load environment variables', e);
}

// initialize mongoDB
mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI);
mongoose.connection.on('error', function(e) {
  errorExit('mongo', 'could not connect to mongoDB', e);
});

// configure app properties
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(body_parser.urlencoded({extended: true}));
app.use(body_parser.json({type: 'application/json'}));

// GET/POST methods using view controller
app.get('/', view_controller.getHome);
app.get('/about', view_controller.getAbout);
app.get('/api/gmaps', view_controller.getGMaps);
app.get('/api/request/bingweb', view_controller.requestBingWeb);
app.get('/api/request/justdial', view_controller.requestJustdial);
app.get('/api/scrape/imdb', view_controller.scrapeIMDb);
Example #20
0
function disconnect() {
    mongoose.connection.close();
};
Example #21
0
process.on('SIGTERM', function(){
  mongoose.connection.close(function(){
    console.log("Mongoose disconnected through app termination. (SIGTERM)");
    process.exit(0);
  });
});
Example #22
0
var mongoose = require('mongoose');

// this connects us to our database - FUCKING IMPORTANT
var connectionString = process.env.DB;

console.log('Attempting to connect to MongoDB');
mongoose.connect(connectionString); // connect to the DB supplied in the connectionString

mongoose.connection.on('connected', function() {
  console.log('Mongoose connected to: ' + connectionString);
});

mongoose.connection.on('error', function(error) {
  console.log('Mongoose has encountered an error: ' + error);
});

mongoose.connection.on('disconnected', function() {
  console.log('Mongoose has disconnected from: ' + connectionString);
});
Example #23
0
 * Main application file
 */

'use strict';

// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development';

var express = require('express');
var mongoose = require('mongoose');
var config = require('./config/environment');

// Connect to MongoDB
mongoose.connect(config.mongo.uri, config.mongo.options);
mongoose.connection.on('error', function(err) {
  console.error('MongoDB connection to <'+ config.mongo.uri + '> failed: ' + err);
  process.exit(-1);
});

// Populate databases with sample data
if (config.seedDB) { require('./config/seed'); }

// Setup server
var app = express();
var server = require('http').createServer(app);
var socketio = require('socket.io')(server, {
  serveClient: config.env !== 'production',
  path: '/socket.io-client'
});
require('./config/socketio')(socketio);
require('./config/express')(app);
require('./routes')(app);
Example #24
0
 function cleanUp() {
   mongoose.connection.removeListener("connected", onConnected);
   mongoose.connection.removeListener("error", onError);
 }
Example #25
0
var fs = require('fs');

/**
* connect to mongodb
*/
var db = null;
var connect = function(){
        
        var options = {server: {socketOptions: {keepAlive: 1} }};
        db = mongoose.connect(config.db, options);
};


//connect error handler

mongoose.connection.on('error',function(err){
});

//reconnect when colosed
//max count 
var MAX_RECONNECT_COUNTER = 10 ;
var reconnect_count = 0;
mongoose.connection.on('disconnected', function(){
    
    connect();
    if(reconnect_count > MAX_RECONNECT_COUNTER){
        process.exit(1);
        reconnect_count = 0;
    } 

    reconnect_count++;
});
Example #26
0
 mongoose.connection.db.dropDatabase(function (err) {
   mongoose.connection.close(done);
 });
Example #27
0
var mongoose = require('mongoose');
var db = 'mongodb://localhost/update-json';

mongoose.connect(db);

//log messages to the console
mongoose.connection.on('connected', function(){
	console.log('Mongoose connected to ' + db);
});

mongoose.connection.on('error', function(err){
	console.log('Mongoose connection error: ' + err);
});

mongoose.connection.on('disconnected', function(){
	console.log('Mongoose disconnected');
});

process.on('SIGINT', function() {
	mongoose.connection.close(function () {
		console.log('Mongoose disconnected through app termination');
		process.exit(0);
	});
});

exports.mongoose = mongoose;
Example #28
0
mongoose.connection.on('open', function () {
  console.error('mongo is open');
 
  // empty the collection
  A.remove(function (err) {
    if (err) throw err;
 
    console.error('removed old docs');
 
    // store an img in binary in mongo
    var a = new A;
    a.img.data = fs.readFileSync(imgPath);
    a.img.contentType = 'image/png';
    a.save(function (err, a) {
      if (err) throw err;
 
      console.error('saved img to mongo');
 
      // start a demo server
      var server = express.createServer();
      server.get('/', function (req, res, next) {
        A.findById(a, function (err, doc) {
          if (err) return next(err);
          res.contentType(doc.img.contentType);
          res.send(doc.img.data);
        });
      });
 
      server.on('close', function () {
        console.error('dropping db');
        mongoose.connection.db.dropDatabase(function () {
          console.error('closing db connection');
          mongoose.connection.close();
        });
      });
 
      server.listen(3333, function (err) {
        var address = server.address();
        console.error('server listening on http://%s:%d', address.address, address.port);
        console.error('press CTRL+C to exit');
      });
 
      process.on('SIGINT', function () {
        server.close();
      });
    });
  });
 
});
Example #29
0
process.on('SIGINT', function() {
    mongoose.connection.close(function () {
        console.log('Mongoose default connection disconnected through app termination');
        process.exit(0);
    });
});
Example #30
0
var mongoose = require('mongoose'),
	Invoice = require('../../lib/entities').Invoice,
	InvoiceBuilder = require('../builders/invoice_builder.js'),
	Customer = require('../../lib/entities').Customer,
	CustomerBuilder = require('../builders/customer_builder.js'),
	Company = require('../../lib/entities').Company,
	CompanyBuilder = require('../builders/company_builder.js'),
	Activity = require('../../lib/entities').Activity,
	ActivityBuilder = require('../builders/activity_builder.js'),
	should = require('should'),
	mongooseTestHelper = require('./persistence_spec_functions.js'),
	validationHelper = require('./mongoose_validation_helper.js'),
	equalityHelper = require('../equality_functions.js');
	
mongoose.connect('mongodb://localhost/therabbithole_test');
mongoose.connection.collection('invoices').drop();

describe('given a new invoice', function() {
	
	var invoice = null,
		error = null;

	beforeEach(function() {
		invoice = new InvoiceBuilder().build();
	});

	describe('when it is saved with none of its required fields filled in', function() {
		
		beforeEach(function(done) {
			invoice = new Invoice(); // the invoice reference by default points to a properly filled in instance
			invoice.save(function(err) {