Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing MongoDB Chapter 3

Connecting Mongoose to MongoDB


Once Mongoose is installed, we have to connect it to the MongoDB in order to start


working with it. This is pretty straightforward with Mongoose; we just have to add a piece
of code to require Mongoose in our app.js file and use the mongoose.connect method


to connect it to the database. Let's go ahead and do that. In the app.js file, add the


following code:


var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

This will import the Mongoose module into our codebase.


Now, to connect to the MongoDB database, add the following line of code in our app.js:


var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var app = express();

//connect to mongodb
mongoose.connect('mongodb://localhost:27017/express_app', function() {
console.log('Connection has been made');
})
.catch(err => {
console.error('App starting error:', err.stack);
process.exit(1);
});

// Require file system module
var fs = require('file-system');
Free download pdf