If you want to establish a connection with the database, avoid using
mongoose.connect('mongodb://127.0.0.1:27017');
Instead, use the following:
mongoose.connect('mongodb://127.0.0.0.1:27017/yourDatabaseName');
Refer to the documentation for more information.
Mongoose requires a specific database name in the connect()
method.
Your final version of app.js
should look like this:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var Developer = require('./models/developers');
var app = express();
// Set up view engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use('/', indexRouter);
app.use('/users', usersRouter);
// Connect to Database
mongoose.connect('mongodb://127.0.0.1:27017/my_unique_database_name');
// API Routes
var router = express.Router();
// Prefix routes with /api
app.use('/api', router);
// Handle 404 errors and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// Error handling
app.use(function(err, req, res, next) {
// Set error parameters based on environment
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// Render error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
// Test Route
router.get('/', function (req, res) {
res.json({message: 'Welcome to my simple API!'});
});
router.route('/developers')
.post(function (req, res) {
var developer = new Developer(); // Create new developer instance
developer.firstName = req.body.firstName;
developer.lastName = req.body.lastName;
developer.jobTitle = req.body.jobTitle;
developer.save(function (err) {
if (err) {
res.send(err);
} else {
res.json('Developer was successfully fetched');
}
});
})
.get(function (req, res) {
Developer.find(function (err, developers) {
if (err) {
res.send(err);
} else
res.json(developers);
});
});
router.route('/developer/:developer_id')
.get(function (req, res) {
Developer.findById(res.params.developer_id, function (err, developer) {
if (err) {
res.send(err);
}
res.json(developer);
});
});
router.route('/developer/firstName/:firstName')
.get(function (req, res) {
Developer.find({firstName:res.params.firstName}, function (err, developer) {
if (err) {
res.send(err);
}
res.json(developer);
});
});