How to use the mongoose.connection function in mongoose

To help you get started, we’ve selected a few mongoose examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github WizardL / NekoPost / backend / db.js View on Github external
return new Promise(async (resolve, reject) => {

    mongoose.connection
      .on('error', error => reject(error))
      .on('close', () => console.log(`[${'!'.red}]Database connection closed`))
      .once('open', () => resolve(mongoose.connections[0]))
    
    try {
      await mongoose.connect(uri)
    } catch (error) {
      reject(error)
    }

    // Gracefully shutdown when INTERRUPT signal occurred
    process.on('SIGINT', () => mongoose.connection.close(() => process.exit(0)))
  })
github Dereje1 / Pinterest-Clone / server / models / db.js View on Github external
// create one place for db connection
// Bring Mongoose into the app
const mongoose = require('mongoose');

// Build the connection string
// const dbURI = 'mongodb://localhost:27017/votingapp';
const dbURI = process.env.MONGOLAB_URI;
mongoose.Promise = global.Promise;
// Create the database connection
mongoose.connect(dbURI, { useMongoClient: true });

// CONNECTION EVENTS
// When successfully connected
mongoose.connection.on('connected', () => {
  console.log(`Mongoose default connection open to ${dbURI}`);
});

// If the connection throws an error
mongoose.connection.on('error', (err) => {
  console.log(`Mongoose default connection error:  ${err}`);
});

// When the connection is disconnected
mongoose.connection.on('disconnected', () => {
  console.log('Mongoose default connection disconnected');
});

// If the Node process ends, close the Mongoose connection
process.on('SIGINT', () => {
  mongoose.connection.close(() => {
github hemakshis / Basic-MERN-Stack-App / app.js View on Github external
const bodyParser = require('body-parser');
const path = require('path');
require('dotenv').config();

const articles = require('./routes/articlesRoute.js');
const users = require('./routes/usersRoute.js');
const config = require('./config.js');

const MONGODB_URI = config.mongodburi || 'mongodb://localhost:27017/basic-mern-app';
const PORT = process.env.PORT || 5000;

mongoose.connect(MONGODB_URI, { useNewUrlParser: true });
mongoose.connection.on('connected', () => {
    console.log('Connected to MongoDB');
});
mongoose.connection.on('error', (error) => {
    console.log(error);
});

let app = express();

// Body Parser Middleware
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

app.use(express.static(path.join(__dirname, 'client/build')));

app.use((req, res, next) => {
     res.header("Access-Control-Allow-Origin", "*");
     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
     if (req.method === 'OPTIONS') {
         res.header("Access-Control-Allow-Methods", "PUT, POST, DELETE, GET");
github TYRMars / React-StepPitGuide / code / Express / server / server.js View on Github external
const express = require('express')
const mongoose = require('mongoose')
//链接mongodeb
const DB_URL = 'mongodb://127.0.0.1:27017/test'
mongoose.connect(DB_URL)
mongoose.connection.on('connected',function () {
  console.log('mongo connnect success');
})
//类似于mysql的表 mongo里有文档、字段的概念
const User = mongoose.model('user', new mongoose.Schema({
  user:{type:String,require:true},
  age:{type:Number,require:true}
}))
//新增数据
// User.create({
//   user:'zhangjianan',
//   age:21
// },function (err,doc) {
//   if (!err) {
//     console.log(doc);
//   }else{
//     console.log(err);
github codingfriend1 / meanbase / server / config / express.js View on Github external
app.set('views', config.root + '/server/views');
  app.set('view engine', 'jade');
  app.use(compression());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
  app.use(methodOverride());
  app.use(cookieParser());
  app.use(passport.initialize());

  // Persist sessions with mongoStore
  // We need to enable sessions for passport twitter because its an oauth 1.0 strategy
  app.use(session({
    secret: config.secrets.session,
    resave: true,
    saveUninitialized: true,
    store: new mongoStore({ mongoose_connection: mongoose.connection })
  }));

  if ('production' === env) {
    // app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
    app.use(express.static(path.join(config.root, 'public')));
    app.set('appPath', path.join(config.root, 'public'));
    app.set('appAppPath', path.join(config.root, 'public', 'app'));
    app.set('adminPath', path.join(config.root, 'public', 'admin/'));
    app.set('themesFolder', path.join(config.root, 'public', 'themes', '/'));
    app.set('extensionsFolder', path.join(config.root, 'public', 'extensions', '/'));
    app.set('frontEnd', 'public');
    app.use(morgan('dev'));
  }

  if ('development' === env || 'test' === env) {
    app.use(require('connect-livereload')());
github eldimious / nodejs-api-showcase / data / infrastructure / db / connector / index.js View on Github external
module.exports = (dbConnectionString) => {
  if (!dbConnectionString) {
    throw new Error('add correct format of config with dbConnectionString');
  }
  const options = {
    useMongoClient: true,
    promiseLibrary: require('bluebird'),
  };

  // Check for errors on connecting to Mongo DB
  mongoose.connection.on('error', (err) => {
    logging.error(`Error! DB Connection failed. Error: ${err}`);
    return err;
  });

  // Connection opened successfully
  mongoose.connection.once('open', () => {
    logging.info('Connection to MongoDB established');
  });

  mongoose.connection.on('disconnected', () => {
    logging.info('Connection to MongoDB closed');
    logging.info('-------------------');
  });

  return {
    getConnection() {
github RisingStack / graffiti-mongoose / src / setup-tests.spec.js View on Github external
after((done) => {
  mongoose.models = {};
  mongoose.modelSchemas = {};
  mongoose.connection.close(() => done());
});
github abrarShariar / invoice-app / node-api / app / migration / product.migration.js View on Github external
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/invoiceDB');
//schema for area
var productSchema = mongoose.Schema({
    id: String,
    name: {type: String, unique: true, dropDups: true},
    rate: Number,
    description: String,
    status: Boolean,
    vat: String
});
var Product = mongoose.model('product', productSchema);

var db = mongoose.connection;
db.on('error', function () {
    console.log('error in connection');
});

db.once('open', function () {
    var data_array = [
        new Product({name: '256Kbps', rate: 500, description: '', status: true, vat: '10'}),
        new Product({name: '512Kbps', rate: 600, description: '', status: true, vat: '10'}),
        new Product({name: '1Mbps', rate: 1000, description: '', status: true, vat: '10'}),
        new Product({name: '2Mbps', rate: 2000, description: '', status: true, vat: '10'}),
        new Product({name: '3Mbps', rate: 3000, description: '', status: true, vat: '10'}),
        new Product({name: '3Mbps', rate: 3000, description: '', status: true, vat: '10'}),
        new Product({name: '4Mbps', rate: 4000, description: '', status: true, vat: '10'}),
        new Product({name: '5Mbps', rate: 5000, description: '', status: true, vat: '10'})
    ];
github eclipse / orion.client / modules / orionode / lib / metastore / mongodb / store.js View on Github external
api.getOrionEE().on("close-server", function() {
		logger.info("Closing MongoDB");
		if (mongoose && (mongoose.connection.readyState === 1 || mongoose.connection.readyState === 2)) {
			mongoose.disconnect();
		}
	});
}
github Hughp135 / angular-5-chat-app / back-end / src / websocket / voice-channel / join.spec.ts View on Github external
after(async () => {
    await mongoose.connection.close();
  });
  beforeEach(async () => {