Let's follow these steps to create a connection to MongoDB and read how many posts we currently have saved in our mean-db database:
- First, we will need to import Mongoose into our Express application. We will do this by creating a new database.js file in the root of our project that we will use to configure our database configuration between our application and MongoDB. We will simply connect to MongoDB through a path to our local machine, and the specific database we want to use: mongodb://localhost/mean-db . We will also export this reference to our mean-db connection in case we may need it in other parts of our application:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mean-db');
module.exports = mongoose.connection;
- Connecting to MongoDB is an asynchronous process, so we will use a promise to notify us when the connection succeeds or fails:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mean-db').then(function() {
console.log('connected to mongodb!');
}, function(error) {
console.error('failed to connect to MongoDB...', error);
});
module.exports = mongoose.connection;
- Now, after we get connected, we can request content from our databases, such as how many posts are saved in it:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mean-db').then(function() {
console.log('connected to mongodb!');
db.collection('post').count().then(function(count) {
console.log("post count: " + count);
});
}, function(error) {
console.error('failed to connect to MongoDB...', error);
});
module.exports = mongoose.connection;
- To use our new MongoDB database connection, we simple need to add it to our app.js Express configuration file in the root of our project:
...
var db = require('./database');
...
- By restarting our Express application, we will see our connection status and post count logged to the console. If there is a connection error, or if our connection is terminated while our application is running, we will also see an error for that:
connected to mongodb!
post count: 1