Skip to content

Instantly share code, notes, and snippets.

@mistical2008
Forked from remarkablemark/README.md
Last active March 21, 2021 10:26
Show Gist options
  • Select an option

  • Save mistical2008/d1f764796fdb4e5a7faf8d6561e2518a to your computer and use it in GitHub Desktop.

Select an option

Save mistical2008/d1f764796fdb4e5a7faf8d6561e2518a to your computer and use it in GitHub Desktop.
How to connect to MongoDB with mongoose

How to connect to MongoDB with mongoose

See associated video.

Install

$ git clone https://gist.github.com/98a60b5ee632b94e6353af3b632246d3.git mongoose
$ cd mongoose
$ npm install

Run

First start mongod:

$ mongod

Then connect to database:

$ node connection
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/dbname');
var connection = mongoose.connection;
connection.on('connected', function() {
console.log('connected to db');
});
connection.on('disconnected', function() {
console.log('disconnected to db');
});
connection.on('error', function(error) {
console.log('db connection error', error);
});
process.on('SIGINT', function() {
connection.close(function() {
console.log('db connection closed due to process termination');
process.exit(0);
});
});
module.exports = connection;
{
"dependencies": {
"mongoose": "^4.7.6"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment