VI.3 RESTful WS - Express and Moongose
1. Make new folder: models.2. Define a new model schema to handle data. Inside models folder, create new file: ismuser.js, then paste the following code:var mongoose = require('mongoose'), Schema = mongoose.Schema;var ismuserSchema = new Schema({ name: { type: String }, age: { type: Number }, role: { type: String, enum: ['Administrator', 'Teacher', 'Student', 'Coordinator']} });// Export ismUser model to use later in ismusers.js file.module.exports = mongoose.model('ismUser', ismuserSchema);3. Add connection to mongodb in app.js.var express = require('express') , routes = require('./routes') , http = require('http') , path = require('path');var mongoose = require('mongoose'); //MongoDB supportvar app = express();app.set('port', process.env.PORT || 3000);app.use(express.favicon());app.use(express.logger('dev'));
app.use(express.bodyParser());app.use(express.methodOverride());app.use(app.router);if ('development' == app.get('env')) { app.use(express.errorHandler()); }app.get('/', routes.index);mongoose.connect('mongodb://localhost/ismusers', function(err, res) {if(err) { console.log('ERROR: connecting to Database. ' + err); }else { console.log('MongoDB connected!')}});http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });4. Open a Linux console to run mongo server:$ mongod5. Run app.js as nodejs application.6. Check in Eclipse Console window, message:Express server listening on port 3000MongoDB connected!